You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:如何提取字符串中'-'与'H'之间的小时数字?

提取'-'与'H/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 uppercase H or lowercase h
  • 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:

  1. s.split('- ', 1)[1]: Splits the string once at - , grabbing the portion after the dash (e.g., "8h by day" for the first string)
  2. after_dash.split('H')[0].split('h')[0]: First tries splitting on H (for the second string), if that doesn't work, splits on h (for the first string), then takes the first segment which is our target number.

内容的提问来源于stack exchange,提问作者Pedro Alves

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:11:05