1

Learning Python here: I am simply trying to switch characters in a string. Example: 'A' to 'C'. The string just isn't doing anything. Here is what I have so far:

import string
dummy = "beans"
for i in xrange(len(dummy)):
    chr(ord(dummy[i])+5)
print(dummy)

4 Answers 4

1

Remember that strings are immutable, so you will need to re-assign your original string. You can try something along these lines:

dummy = "beans"
newdummy = ""
for i in xrange(len(dummy)):
    newdummy += chr(ord(dummy[i])+5)
dummy = newdummy
print(dummy)

This would be a more Pythonic approach:

dummy = ''.join(chr(ord(c) + 5) for c in dummy)
print(dummy)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, I am used to C++ so Python seems a bit... different :)
@AlexanderGardner Yep glad I could help :-) Yea Python offers many utilities that are not available in languages like C++, so it takes time to get used to. Anyway, don't forget to accept an answer!
1

the string.maketrans should be more elegant here:

import string

src = string.ascii_letters
dst = string.ascii_letters[5:] + string.ascii_letters[:5]
trans = string.maketrans(src, dst)
new_dummy = dummy.translate(trans)

for details, please reference the doc of string.maketrans.

Comments

0

Strings in python are immutable. This means that you cannot change them, so you'll have to reassign the variable to a new string instead.

Here's an example:

import string
dummy = "beans"
for i in xrange(len(dummy)):
    dummy = dummy[:i] + chr(ord(dummy[i])+5) + dummy[i+1:]
print(dummy)

Or a shorter way:

dummy = "beans"
dummy = "".join([chr(ord(c)+5) for c in dummy])

Comments

0

You can do this by doing:

mystring="hello"
newstring=""
for x in range(len(mystring)):
    newstring+=chr(ord(mystring[x])+5)

however, please know that if you do this, and you get up to 251 in the ASCII value, adding 5 will throw an error, so you should check whatever value you are using with an if statement like:

if ord(character)+value<255:
    ##your ok
else:
    ##uh oh...

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.