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,982
  • 5
  • 55
  • 87
Jazzmine
  • 1,837
  • 8
  • 36
  • 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

9
 >>> 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
  • 49,085
  • 60
  • 166
  • 233
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,711
  • 2
  • 30
  • 48
  • 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
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
  • 26,748
  • 2
  • 58
  • 81
2
>>> s = '501,555,570=3.5'
>>> others, last = s.rsplit(',', 1)
>>> last
'570=3.5'
wim
  • 338,267
  • 99
  • 616
  • 750
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
  • 3,134
  • 1
  • 20
  • 32
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
  • 59,869
  • 19
  • 150
  • 156
1

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

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