the index of the string
A string is a combination of a series of characters, so we can 方括号
obtain a single character by adding a sequence number to the operator symbol.
words = 'Python'
print(words[1])
y
print(words[0])
P
print(words[-1])
n
The above method is applicable to the string type of words, but if it is a relatively long string, such as papers, poems, then this method is not applicable, we can use the len function to realize the index of the string
words = '你吃饭了吗'
length = len(words)
print('长度:', length)
print('最后一个元素是:', words[length-1])
Built-in len
functions can help us count the length of a string. Since ordinals start at 0, the length minus 1 is our last character's ordinal.
!
I can pass two parameters to print, separated by English in the middle (be sure to follow the rule that all other parameters are English characters, otherwise an error will be reported.)
type
name is a string type variable
age is an integer type variable
variable of floating point type
[In Python, you can use the type function to view the variable type]
Right now:
It can be checked as the name followed by the class to indicate the type they belong to
str is a string type
int represents an integer type
float represents the floating point type
The purpose of confirming the variable type is to confirm the variable type before the program operates, so as to ensure that the program execution is meaningful and logically correct.
[Be careful: If a number is enclosed in quotation marks, such as: print("123"), it will also be regarded as a string type]
Taking variable names is to avoid using reserved words as much as possible, so as not to cause unnecessary trouble
string slice
A part of a string is called a slice, eg "吃饭"
relative to "你吃饭了吗"
. We can also use the square bracket operator to get a slice of the string, the way to get it is [a:b]
. Where a
is the start sequence number and b
the end sequence number.
Note that the obtained slice contains a
does not contain b
words = '你吃饭了吗'
sliced = words[2:4]
print(sliced)
output: meal
When we a
leave it empty, the slice results in all characters that b
were not included before . b
When we b
set it to empty, the result of the slice is all characters a
after and including a
.
words = '你吃饭了吗'
print(words[:4])
print(words[2:])
output: you have eaten
output: Have you eaten yet?
When a
it is equal b
, the return result is an empty string, and when a
both b
are empty, it returns the copy object of the current string.
words = '你吃饭了吗'
print(words[2:2])
print(words[:])
output:
output: have you eaten
in operator
in
The operator can receive a string on the left and right, judge whether the string on the left is contained in the string on the right, and return an object bool
.
Functions related to strings