Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

tashzol
tashzol
1,354 Points

String manipulation

I have encountered a problem that I can't seem to solve as I am still beginner in learning Python. Is it possible to manipulate a given string in Python to change all the occurrences of characters around, for example:

'aaabbbccc' --> change the a to b, and b to a so it becomes 'bbbaaaccc'

or

'aabbcc' to become 'bbaacc'.

I understand that strings are immutable and need to be converted to lists/tuples or slice into single chars but I don't understand how to do this.

If I do try to replace

print('aaabbbccc'.replace('a', 'b')

I get bbbbbbccc... but I need all my 'b' characters to become 'a' characters as well so I get 'bbbaaaccc' as a result, in case of any number of characters in the string given. Is this possible? Thanks!

3 Answers

Steven Parker
Steven Parker
230,274 Points

Using "replace" is a good idea, it gives you a new string based on changing the original. But you need an intermediate character so you don't get the old "b"s confused with the new ones, and then you can chain the operations in sequence:

print('aaabbbccc'.replace('a', '$').replace('b', 'a').replace('$', 'b'))

There's also a slightly more complicated function that will translate both in one operation:

print("aaabbbccc".translate({97:'b', 98:'a'}))
tashzol
tashzol
1,354 Points

This is fantastic - I thought about taking in additional step for a moment today, but I couldn't have figured out how to do it. And this is the first time I am hearing about the translate function - I am going to do some research on it! Thanks :-))!