** * This article is from Udemy "[Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style](https://www.udemy.com/course/python-beginner/" Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style ")" It is a class notebook for myself after taking the course of. It is open to the public with permission from the instructor Jun Sakai. ** **
index
word = 'python'
print(word[0])
print(word[1])
print(word[2])
print(word[3])
print(word[4])
print(word[5])
result
p
y
t
h
o
n
When you assign a string to a variable, you can specify any character in that string. Note that in Python, the index for ** "first character" is "0" **.
index
word = 'python'
print(word[100])
result
print(word[100])
IndexError: string index out of range
At this time, if an index exceeding the range of the character string is specified, an error will occur.
index
word = 'python'
print(word[-1])
print(word[-2])
print(word[-3])
result
n
o
h
[-1]
etc. are counted so that they go further to the left from the first character ([0]
) and turn to the last character.
Therefore, [-1]
is an index representing the last character.
slice
word = 'python'
print(word[0:2])
result
py
With [:]
, you can specify the start point and end point, and specify the number between them.
|p|y|t|h|o|n|
0 1 2 3 4 5 6
The index actually represents between letters, and it is easy to understand if you think in this way. (Between 0 and 2 is "py".)
slice
word = 'python'
print(word[:2])
print(word[2:])
print(word[:])
result
py
thon
python
If you omit the start point, it will be "from the beginning", If the end point is omitted, it will be "until the end". If both the start point and the end point are omitted, the entire character string will be specified.
◆「python」→「jython」
change_letter
word = 'python'
word = 'j' + word[1:]
print(word)
result
jython
count_letters
word = 'python'
n = len(word)
print(n)
result
6
The "length" of a string can be counted using len ()
.
Recommended Posts