如何提取字符串中第n个单词及循环指定序号的目标数字?
Solutions for Your String Processing Requirements
Got it, let's tackle your two requirements step by step with clear code examples that fit your needs!
1. Extract the nth Word from a String
To pull out the nth word (where n=1 refers to the first word), we can split the string into a list of words, then index into that list (adjusting for 0-based indexing in most programming languages). Here's a Python implementation:
def get_nth_word(input_str: str, n: int) -> str | None: # Split the string into words (handles multiple spaces/tabs automatically) word_list = input_str.split() # Check if n is within a valid range (1-based) if 1 <= n <= len(word_list): return word_list[n - 1] else: # Return None if n is out of bounds, or you could raise an error instead return None # Example usage test_string = "The quick brown fox jumps over the lazy dog" print(get_nth_word(test_string, 4)) # Output: "fox"
2. Extract the i-th Occurrence of a Numeric Word in Lines
For this task, we'll loop through each line, check each word to see if the next word is a number, keep a running count of these occurrences, and return the number when we hit the i-th match. Here's how to do it in Python:
def get_i_th_numeric_word(lines: list[str], target_index: int) -> str | None: occurrence_count = 0 for line in lines: words = line.split() # Iterate up to the second-last word to avoid index errors for idx in range(len(words) - 1): next_word = words[idx + 1] # Check if the next word is a digit (adjust if you need to handle negatives/floats) if next_word.isdigit(): occurrence_count += 1 if occurrence_count == target_index: return next_word # Return None if we don't find the target occurrence return None # Example usage (matches your requested output: 10, 20, 30 for i=1,2,3) sample_lines = [ "Start here 10 first number", "Middle section 20 second number", "End part 30 third number" ] print(get_i_th_numeric_word(sample_lines, 1)) # Output: "10" print(get_i_th_numeric_word(sample_lines, 2)) # Output: "20" print(get_i_th_numeric_word(sample_lines, 3)) # Output: "30"
Quick Notes:
- If you need to handle negative numbers or floats (like "-10" or "3.14"), replace
next_word.isdigit()with a try-except block:try: float(next_word) is_numeric = True except ValueError: is_numeric = False - The code uses 1-based indexing for
target_index, which aligns perfectly with your requirement (i=1= first occurrence).
内容的提问来源于stack exchange,提问作者user9402789
相关产品推荐
相关产品推荐

