Python:如何提取字符串中'-'与'H'之间的小时数字?
Hey there! Let's first break down why your original code threw that error:
Your code used myString.split("H",1)[1], but the first input string has a lowercase h instead of uppercase H. When you split on "H" for that string, the result is a list with only one element (since there's no "H" to split on), so trying to access index [1] triggers the IndexError you saw.
Now, here are two reliable ways to get the hour numbers you need:
Method 1: Regular Expressions (Most Flexible)
Regex is ideal here because it handles both uppercase H and lowercase h seamlessly, and directly targets the number between - and the H/h character.
import re # Your input strings input_strings = ["I have been working - 8h by day", "Like - 9H by Month"] hours = [] for s in input_strings: # Match '- ' followed by digits, then either H or h match = re.search(r'- (\d+)[Hh]', s) if match: hours.append(match.group(1)) print(' '.join(hours)) # Output: 8 9
How this works:
r'- (\d+)[Hh]': The regex pattern breaks down like this:-: Matches the dash followed by a space (matches your input format exactly)(\d+): Captures one or more digits (this is the hour number we want)[Hh]: Matches either uppercaseHor lowercaseh
match.group(1)pulls out the captured digit string from the match result.
Method 2: String Splitting (No Regex Required)
If you'd rather avoid regex, you can split the string step by step to handle both H and h:
input_strings = ["I have been working - 8h by day", "Like - 9H by Month"] hours = [] for s in input_strings: # Split once at '- ' to get everything after the dash after_dash = s.split('- ', 1)[1] # Split on either 'H' or 'h' to isolate the number before it hour = after_dash.split('H')[0].split('h')[0] hours.append(hour) print(' '.join(hours)) # Output: 8 9
How this works:
s.split('- ', 1)[1]: Splits the string once at-, grabbing the portion after the dash (e.g., "8h by day" for the first string)after_dash.split('H')[0].split('h')[0]: First tries splitting onH(for the second string), if that doesn't work, splits onh(for the first string), then takes the first segment which is our target number.
内容的提问来源于stack exchange,提问作者Pedro Alves

