Let’s say you need to iterate over of all the characters of a string object and modify every character in some way. You can do it using the for
loop.
>>> s1 = 'Dan Dumitrache'
>>> for i in s1:
... print(i, ' ; ')
...
D ;
a ;
n ;
;
D ;
u ;
m ;
i ;
t ;
r ;
a ;
c ;
h ;
e ;
Here, the iterator pulls each element from the list.
>>> s1 = 'DAN'
>>> for i in s1:
... print(s1.lower())
...
dan
dan
dan
Here, the word dan
is printed three times because we used the for
loop. If you wanted to be printed only once in lowercase letters then just use the print
part without the for
loop.
Here you have another example:
>>> s1 = 'dan'
>>> for i in range(3):
... print(s1[i].upper())
...
D
A
N
However, if you wanted printed on the same line then you can use end = ''
as shown below:
>>> s1 = 'dan'
>>> for i in range(3):
... print(s1[i].upper(), end='')
...
DAN