1

For instance, I have a string like this:

my_string = 'a hello aaaaa hi aaaaaaa bye bbb' 

I want to change 'a' or 'a's to 'b'. So output I want is:

changed_string = 'b hello b hi b bye bbb' 

I tried use replace and then making multiple 'b's to single 'b', but then it would effect multiple 'b's that were originally in the string.

I don't want an answer like do the first n characters.

Any suggestions?

4 Answers 4

5
>>> import re >>> my_string = 'a hello aaaaa hi aaaaaaa bye bbb' >>> re.sub(r'a+', 'b', my_string) 'b hello b hi b bye bbb' 
Sign up to request clarification or add additional context in comments.

2 Comments

sorry to ask you again, but i have problem when i'm converting period(.) to something else.(for instance, b) if i use re.sub(r'.+', 'b', my_string) the result is b... what can i do about this???
@H.Choi That's because . is a special character which mactches any character except newline by default. Escape it with a backslash like \.+. You can see all the special chars here: docs.python.org/library/re.html. Also accept my answer if it helped you :D
2

use regular expression.

depending on your tools, it could be a one-liner or 2-3 line of code.

with vim

s/a+/b/g 

--

ohhh, didn't notice it was python. see jamylak's answer.

Comments

0

Without using regex you could do this, although I would rather use regex since it's much clearer and faster in this case.

>>> from itertools import groupby >>> my_string = 'a hello aaaaa hi aaaaaaa bye bbb' >>> ''.join(''.join(g) if k != 'a' else 'b' for k, g in groupby(my_string)) 'b hello b hi b bye bbb' 

Comments

0
>>> mystring = 'a hello aaaaa hi aaaaaaa bye bbb' >>> ' '.join('b' if set(i)==set(['a']) else i for i in mystring.split()) 'b hello b hi b bye bbb' 

Note that while this works with your example, it will not work with strings where the repeated character is part of a word, such as 'aaaaaz' - It will leave such words untouched, Which may or may not be desirable...

1 Comment

no need for a list comprehension here, remove the [, ] to make it a generator. edit: nvm I don't think it would be that inefficient but regex is certainly faster

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.