Example 00. Sort the character string "stressed" in reverse order.
q00.py
#! usr/bin/pyenv python
# _*_ cording utf-8 _*_
word = "stressed"
print(word[::-1])
q00.Output result of py
desserts
Point Use slices. A slice can extract a part or all of a character string.
word[(start point):(end point):(Number of steps)]
If you want to select everything from the beginning to the end of a word, you can omit the start and end points.
Example 01. Output the odd-numbered character of the character string "Patatokukashi". It also outputs even-numbered characters.
q01.py
#! usr/bin/pyenv python
# _*_ cording utf-8 _*_
word = "Patatoku Kashii"
#Extract odd-numbered characters
extract1 = word[::2]
print(extract1)
#Extract even-numbered characters
extract2 = word[1::2]
print(extract2)
q01.Output result of py
Police car
taxi
Point When using slices, the start point and end point may be omitted unless the character string is definitely determined.
Example 02. "Police car" and "Taxi" are connected alternately from the beginning, and "Patatokukashi" is displayed.
q02.py
#! usr/bin/pyenv python
# _*_ cording utf-8 _*_
word1 = "Police car"
word2 = "taxi"
linking = ""
for (str1, str2) in zip(word1, word2):
linking += (str1 + str2)
print(linking)
q02.Output result of py
Patatoku Kashii
Point In python, multiple objects can be processed in a loop at the same time by using the zip function. However, in the case of multiple objects, the number of executions is adjusted to the one with the smaller number of elements.
Recommended Posts