0

I need to change the number in a string like "Higher id: 38".

I can get "38" with string.split(" ")[2], do you know if there is a simple way to change this value? I tried comment.split(" ")[2] = "55" but it didn't worked.

Am I constrained to do the modification by running manually through the string?

2 Answers 2

3

Strings are immutable, thus you can not modify the string in place. You have to make a new one:

>>> mystr = "Higher id: 38"
>>> mylist = mystr.split(' ')
>>> mylist[-1] = "55" # t[-1] accesses the last element in the list
>>> print ' '.join(mylist)
Higher id: 55

If you are confident that 38 will only occur once in the string, you can use replace(). Just remember that it returns the replaced string, and does not actually replace the string in place:

>>> mystr = "Higher id: 38"
>>> mynewstr = mystr.replace('38', '55')
>>> print mynewstr
Higher id: 55

Or even regex can be used:

>>> import re
>>> print re.sub(r'(\d.*?)$', '55', mystr)
Higher id: 55
Sign up to request clarification or add additional context in comments.

1 Comment

It can be any number so your first solution is the one I needed, thank you!
3
>>> "Higher id: 38".replace('38', '55')
'Higher id: 55'
>>> 

1 Comment

Thank you for your answer but Haidro's is what I needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.