Python - Get string after and before a Character

Pedro Alves picture Pedro Alves · Apr 16, 2018 · Viewed 9.4k times · Source

I've this strings:

"I have been working - 8h by day"
"Like - 9H by Month"

I'm trying to get the number of Hours. Basically I'm trying to get this output:

8
9

I try this but without success:

print(myString.split("H",1)[1] )

But I'm getting this:

builtins.IndexError: list index out of range

How can I get the string after "-" and before "H" in Python?

Thanks!

Answer

galaxyan picture galaxyan · Apr 16, 2018

the issue you have is the "I have been working - 8h by day" has no "H" in it, so when you split by "H" there is only one element in list.

you could find it using regex

import re
pattern = r'\d(?=[h|H])'
data = ["I have been working - 8h by day",
        "Like - 9H by Month"]

for item in data:
    print re.findall(pattern, item)