Vlad Rodikov
Vlad Rodikov

Reputation: 3

How to delete second and etc. symbols in string in Python?

Example. I have this sentence: "Hello__my_beautiful___friends!" I want this: "Hello_my_beautiful_friends!" How can i do this? How to delete 2 or more symbol "_" in string?

Upvotes: 0

Views: 87

Answers (2)

Chrispresso
Chrispresso

Reputation: 4081

You can use re.sub:

In [5]: re.sub('_+', '_', s)
Out[5]: 'Hello_my_beautiful_friends!'

This uses re.sub(patter, replacement, string) where _+ indicates one ore more _ and to replace it with a single underscore.

Upvotes: 3

DaSim
DaSim

Reputation: 363

In this way

my_string = "Hello__my_beautiful___friends!"
while "__" in my_string:
   my_string = my_string.replace("__","_")

Notice that the loop is needed since you may have consecutive "__" to remove and you do that with multiple iterations

Upvotes: 0

Related Questions