I have a long string, that contains
Current: 98%
exactly one time. The percentage can be everything between 0 and 100.
E.g.:
This is a multi-line
output and the battery level is
Current: 100%
Thank you.
How can I just get the value between Current: and %?
CodePudding user response:
You could use an approach such as the one below, using regular expressions.
import re
test = """
This is a multi-line
output and the battery level is
Current: 100%
Thank you.
"""
print(re.search(r'Current: (.*?)%', test).group(1))
EDIT:
If you need an integer out, you can just wrap the final value with int():
result = int(re.search(r'Current: (.*?)%', test).group(1))
CodePudding user response:
Using a regular expression for this exercise is overkill. Instead, find the position of the percent sign, trim the string at that position, split it, and take the last element:
text[:text.index('%')].split()[-1]
# '100'
I assume that there is only one % in the string.
CodePudding user response:
You can use regex groups to pull out the percentage. This will match a numerical value between Current: (with a space) and the % symbol.
import re
text = """This is a multi-line
output and the battery level is
Current: 100%
Thank you."""
pattern = re.compile(r"Current: ([0-9] )%")
result = re.search(pattern, text)
print(result.group(1))
CodePudding user response:
you can use the filter function on a string if you dont like re
int("".join(filter(str.isdigit, long_string)))
