I can't figure out how to properly slice a string. There is a line: "1, 2, 3, 4, 5, 6". The number of characters is unknown, numbers can be either one-digit or three-digit I need to get the last value up to the nearest comma, that means I need to get the value (6) from the string
CodePudding user response:
you can try to split and get last value
string = "1, 2, 3, 4, 5, 6"
string.split(',')[-1]
>>> ' 6'
add strip to get rid of the white spaces
string.split(',')[-1].strip(' ')
>>> '6'
CodePudding user response:
Better use str.rsplit
, setting maxsplit=1
to avoid unnecessarily splitting more than once:
string = "1, 2, 3, 4, 5, 6"
last = string.rsplit(', ', 1)[-1]
Output: '6'
CodePudding user response:
It seems to me the easiest way would be to use the method split
and divide your string based on the comma.
In your example:
string = '1, 2, 3, 4, 5, 6'
last_value = string.split(', ')[-1]
print(last_value)
Out[3]: '6'
CodePudding user response:
Here's a function that should do it for you:
def get_last_number(s):
return s.split(',')[-1].strip()
Trying it on a few test strings:
s1 = "1, 2, 3, 4, 5, 6"
s2 = "123, 4, 785, 12"
s3 = "1, 2, 789654 "
...we get:
print (get_last_number(s1))
# 6
print (get_last_number(s2))
# 12
print (get_last_number(s3))
# 789654