110
E X E R C I S E # 3 6 : R E V E R S E S T R I N G
reverseString('Hello')
→
'olleH'
Strings are immutable in the Python language, meaning you can’t modify their characters the way
you can modify the items in a list. For example, if you tried to change 'Rat' to 'Ram' with the
assignment statement 'Rat'[2] = 'm', you would receive a TypeError: 'str' object
does
not support item assignment
error message. On the other hand,
if you store a string
'Rat' in a variable named animal, the assignment statement animal = 'Ram' isn’t modifying the 'Rat'
string but rather making animal refer to an entirely new string, 'Ram'.
We can modify an existing string is to create a list of single-character strings,
modify the list, and
then create a new string from the list. Enter the following into the interactive shell:
>>> animal = 'Rat'
>>> animal = list(animal)
>>>
animal
['R', 'a', 't']
>>> animal[2] = 'm'
>>> animal
['R', 'a', 'm']
>>> animal = ''.join(animal)
>>> animal
'Ram'
We’ll use this technique to reverse the characters in a string.
Dostları ilə paylaş: