3

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?

Juan Leni
  • 6,196
  • 3
  • 53
  • 81
Jazzmine
  • 1,727
  • 8
  • 33
  • 54
  • Yes, `split()` should work. – 9000 Mar 09 '16 at 16:17
  • @gtlambert: Was the downgrade due to my not putting the sample data in a special code block? – Jazzmine Mar 09 '16 at 16:17
  • I didn't downvote you! I just improved the formatting of your code – gtlambert Mar 09 '16 at 16:18
  • 2
    @jazzime: Downvotes usually come to questions where authors fail to do basic research before asking. – 9000 Mar 09 '16 at 16:18
  • Ok, I've done basic research but didn't see an example of choosing text after the last comma. I saw several examples where there was just one comma. Could someone provide an example in which the text after the last comma is extracted? Thank you – Jazzmine Mar 09 '16 at 16:21

7 Answers7

8

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'
gtlambert
  • 11,253
  • 2
  • 28
  • 47
  • I think all the answers provided worked but as you are first, I've indicated this is the correct answer. However, I did test the s.split(',') approach which also produced the same results. Thanks everyone. – Jazzmine Mar 09 '16 at 16:59
7
 >>> 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'
Andy
  • 46,308
  • 56
  • 161
  • 219
4

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'
L3viathan
  • 25,498
  • 2
  • 53
  • 71
2
>>> s = '501,555,570=3.5'
>>> others, last = s.rsplit(',', 1)
>>> last
'570=3.5'
wim
  • 302,178
  • 90
  • 548
  • 690
2

Another variation, and how I would do it myself:

>>> s = '501,555,570=3.5'
>>> last = s.split(',')[-1]
>>> last
'570=3.5'
DaveBensonPhillips
  • 2,914
  • 1
  • 17
  • 30
2

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'
styvane
  • 55,207
  • 16
  • 142
  • 150
1

You could take substring from the position after where you find the last comma.

s[s.rfind(',') + 1 : ]
dorado
  • 1,485
  • 1
  • 15
  • 38