Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace the some characters from the end of a string?

I want to replace characters at the end of a python string. I have this string:

 s = "123123" 

I want to replace the last 2 with x. Suppose there is a method called replace_last:

 r = replace_last(s, '2', 'x')  print r  1231x3 

Is there any built-in or easy method to do this?

like image 616
Freewind Avatar asked Sep 09 '10 09:09

Freewind


People also ask

How do you remove special characters from the end of a string?

Try following code: str = str. replaceAll("\\/$", "");

How do you replace certain letters in a string?

Using 'str.replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.

How do I change the end of a string?

Use the String. replace() method to replace the last character in a string, e.g. const replaced = str.


Video Answer


2 Answers

This is exactly what the rpartition function is used for:

rpartition(...) S.rpartition(sep) -> (head, sep, tail)

Search for the separator sep in S, starting at the end of S, and return the part before it, the separator itself, and the part after it.  If the separator is not found, return two empty strings and S. 

I wrote this function showing how to use rpartition in your use case:

def replace_last(source_string, replace_what, replace_with):     head, _sep, tail = source_string.rpartition(replace_what)     return head + replace_with + tail  s = "123123" r = replace_last(s, '2', 'x') print r 

Output:

1231x3 
like image 188
Mizipzor Avatar answered Sep 21 '22 17:09

Mizipzor


Using regular expression function re.sub to replace words at end of string

import re s = "123123" s = re.sub('23$', 'penguins', s) print s 

Prints:

1231penguins 

or

import re s = "123123" s = re.sub('^12', 'penguins', s) print s 

Prints:

penguins3123 
like image 21
Tony Ingraldi Avatar answered Sep 22 '22 17:09

Tony Ingraldi