Alexander Gardner
Alexander Gardner

Reputation: 31

Python String Manipulation Concerns

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)

Upvotes: 1

Views: 122

Answers (4)

IT Ninja
IT Ninja

Reputation: 6430

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...

Upvotes: 0

chuchao333
chuchao333

Reputation: 1518

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.

Upvotes: 1

grc
grc

Reputation: 23545

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])

Upvotes: 0

arshajii
arshajii

Reputation: 129477

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)

Upvotes: 1

Related Questions