Pedro Alves
Pedro Alves

Reputation: 1054

Python - Get string after and before a Character

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!

Upvotes: 1

Views: 14012

Answers (4)

Ryan Schaefer
Ryan Schaefer

Reputation: 3120

There is a danger with this that it will split on other Hs and that it keeps the whole string (to resolve this write a better expression with regex).

to resolve your code as is:

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

Upvotes: 0

galaxyan
galaxyan

Reputation: 6141

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)

Upvotes: 1

Ajax1234
Ajax1234

Reputation: 71471

You can use re.findall to match all digits only if followed by an h or H:

import re
s = ["I have been working - 8h by day", "Like - 9H by Month"]
new_s = [re.findall('\d+(?=H)', i, flags=re.I)[0] for i in s]

Output:

['8', '9']

Upvotes: 0

Rakesh
Rakesh

Reputation: 82795

Use regex

Ex:

import re

s = ["I have been working - 8h by day", "Like - 9H by Month"]
for i in s:
    print(re.findall("\d+H" ,i, flags=re.I))

Output:

['8']
['9']

Upvotes: 0

Related Questions