Iterate over all characters
Since a character can be accessed by index, you can use a variable loop to iterate over all characters, which will take on possible index values. For example, a program that displays all the character codes of the string
s
would look like this
for i in range(len(s)):
print(s[i], ord(s[i]))
Explanations for the program:
1) The
len(s)
function finds the length of a string. The index of the first character is 0 and the index of the last is len(s)-1. The loop variable
i
will just take values sequentially from
0
to
len(s)-1
.
2) In each line, the symbol itself will be displayed first, and then its code, which is returned by the built-in function
ord().
The same enumeration can be written shorter:
for c in s:
print(c, ord(c))
In this fragment, the loop header loops through all the characters s, placing them in turn in the variable
c
.
As already mentioned, the peculiarity of Python when working with strings is that strings are immutable objects. In other words, we cannot change individual characters of a string.
For example, the following statement will not work
s[5]='a'
But you can compose a new line from the characters with the required changes.
Task
In the input string, replace all characters 'a' to characters 'b'.
s = input()
sNew = ""
for c in s:
if c == 'a': c = 'b'
sNew += c
print(sNew)
In this program, the loop goes through all the characters of the string s. In the body of the loop, we check the value of the variable
с
: if the symbol matches the symbol '
a
', then we replace it with '
b< /code>' and add it to the end of the new line sNew
using the addition operator.
This option is rather slow.
In the future, we'll take a look at the built-in string manipulation functions and learn how to do it faster.