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!
galaxyan :
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.\n\nyou could find it using regex\n\nimport re\npattern = r'\\d(?=[h|H])'\ndata = [\"I have been working - 8h by day\",\n \"Like - 9H by Month\"]\n\nfor item in data:\n print re.findall(pattern, item)\n",
2018-04-16T14:11:10
Rakesh :
Use regex\n\nEx:\n\nimport re\n\ns = [\"I have been working - 8h by day\", \"Like - 9H by Month\"]\nfor i in s:\n print(re.findall(\"\\d+H\" ,i, flags=re.I))\n\n\nOutput:\n\n['8']\n['9']\n",
2018-04-16T14:09:41
Ajax1234 :
You can use re.findall to match all digits only if followed by an h or H:\n\nimport re\ns = [\"I have been working - 8h by day\", \"Like - 9H by Month\"]\nnew_s = [re.findall('\\d+(?=H)', i, flags=re.I)[0] for i in s]\n\n\nOutput:\n\n['8', '9']\n",
2018-04-16T14:09:50