ASCII in Python

Asked

Viewed 8,071 times

2

Hi. I’m from C and I’m starting to learn Python. I have a question to move the characters of a string 3 positions and in C would look something like this:

str[i] += 3;

I tried to do the same thing in Python and ended up generating an error. So, how can I advance 3 positions of a character in the Python language?

3 answers

3


A more flexible solution for when you have to make many changes in string is to store it as a list using list:

texto = list("o seu texto aqui")

This makes when you show your content, it appears as a normal list:

>>> texto
['o', ' ', 's', 'e', 'u', ' ', 't', 'e', 'x', 't', 'o', ' ', 'a', 'q', 'u', 'i']

In this way it will be possible to change each position freely, as it was doing:

>>> texto[2] = chr(ord(texto[2]) + 1)
>>> texto
['o', ' ', 't', 'e', 'u', ' ', 't', 'e', 'x', 't', 'o', ' ', 'a', 'q', 'u', 'i']

Note that you cannot simply add a character to a number. First you have to fetch the value ascii of the letter with the function ord, add to the value you want, and convert back to character with chr.

And whenever you want to show again as a normal string, just use the Join method

>>> ''.join(texto)
'o teu texto aqui'
  • Really this way is much more interesting to do. Thanks!

1

Hello, as strings are immutable in Python every operation on top of a string generates a new string. So one way to solve your problem would be:

str="ABBBCD"
index=1
str = str[:index] + chr(ord(str[index]) + 3) + str[index + 1:]
print(str)

0

string = str('SVL#d#wxd#glvflsolqd#suhihulgd$$')

decode = []

for letter in string:

    decoded = int(ord(letter))

    code = chr(decoded + 3)

    decode.append(code)

print(decode)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.