ASCII in Python

2

Hello. I come 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 it ended up causing an error. So, how can I advance 3 positions of a character in the Python language?

    
asked by anonymous 03.02.2018 / 19:47

2 answers

0

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

texto = list("o seu texto aqui")

This causes you to display your content as it appears in a normal list:

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

In this way you can change each of the positions freely as you were 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 can not simply add a caratere with a number. You must first fetch the ascii value of the letter with the ord , add the value you want, and convert back to caratere with chr .

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

>>> ''.join(texto)
'o teu texto aqui'
    
03.02.2018 / 21:23
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)
    
03.02.2018 / 20:09