How to Manipulate Strings in Python

Asked

Viewed 358 times

-1

I was wondering how I can manipulate Python characters. In C, I can do this by adding 1 to a character, if I type "a" for example, it adds 1, and "a" will become "b". Example:

char string[20];
    printf ("Digite uma String: ");
    scanf ("%19[^\n]", string);

    int i;

    for (i = 0; i < strlen(string); i+=1)
    {
            string[i] += 1;
    }

Is there any way I could do something similar in Python? I know there are functions to turn the minuscule letter to upper case and vice versa, but I really wanted to change the letters according to the Ascii Table, change the characters of a string, one by one. You could manipulate the characters of a python string the same way I manipulate in C?

  • 2

    Although I don’t think this is one of the best questions on the site, I don’t see anything that justifies its closure. I voted to reopen.

1 answer

6


Yes, but not as directly as C.

In C, the character 'a' is stored in memory as the byte 01100001, which in decimal is the number 97. When you add 1 to the value, the computer will add 1 to the byte, getting 01100010, which is the number 98 in decimal and the letter 'b' when analyzed as a character.

In Python, objects are much more complex than that. Along with the values themselves there are also implemented numerous fields and methods related to the object and thus will not be able to make a direct relation between a character and a number. However, you can do the same thing that occurs in C, but manually, which is to get the respective decimal related to your character, add 1 and then check what is the character related to the result.

You can use the functions ord and chr.

letra_a = 'a'
inteiro_a = ord(letra_a)
inteiro_b = inteiro_a + 1
letra_b = chr(inteiro_b)

Or just, letra_b = chr(ord('a')+1). The function ord, for the parameter 'a' will return the integer 97. Summed 1 gets 98 that through the function chr the character is obtained 'b'.

Browser other questions tagged

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