I have a column with data like this that I'm accessing via Python:
501,555,570=3.5
I want to get 570=3.5
.
How can I do that? Would it be a variation of the split command?
I have a column with data like this that I'm accessing via Python:
501,555,570=3.5
I want to get 570=3.5
.
How can I do that? Would it be a variation of the split command?
>>> s = '501,555,570=3.5'
>>> s.split(",")[-1]
'570=3.5'
This will access the last element in the split string. It is not dependent on how many commas are in the string.
Example of longer string:
>>> s = "501,555,670,450,1,12,570=3.5"
>>> s.split(",")[-1]
'570=3.5'
You can use the str.rsplit()
function as follows:
In [34]: s = '501,555,570=3.5'
In [35]: s.rsplit(',', 1)[1]
Out[35]: '570=3.5'
A slight variation of wim's answer, if you're in a recent Python 3 version:
>>> s = '501,555,570=3.5'
>>> *others, last = s.split(',')
>>> last
'570=3.5'
>>> s = '501,555,570=3.5'
>>> others, last = s.rsplit(',', 1)
>>> last
'570=3.5'
Another variation, and how I would do it myself:
>>> s = '501,555,570=3.5'
>>> last = s.split(',')[-1]
>>> last
'570=3.5'
Using rpartition
and as @ MartijnPieters♦ mentioned here in his comment.
for a single split,
str.rpartition()
is going to be faster.
>>> s.rpartition(',')[-1]
'570=3.5'
You could take substring from the position after where you find the last comma.
s[s.rfind(',') + 1 : ]