关于Python中字符串的有趣事实 |第 2 组(切片)
关于Python中字符串的有趣事实 -Set 1
与其他编程语言一样,可以使用类似数组的索引语法来访问字符串的单个字符。在这种情况下,我们可以通过索引号访问字符串的每个元素,并且索引从 0 开始Python会进行索引越界检查。
因此,我们可以使用语法string_name[index_position]获得所需的字符:
- 正 index_position 表示从开始(0)开始的元素,负索引表示从结束(-1)开始的索引。
例子:
# A python program to illustrate slicing in strings
x = "Geeks at work"
# Prints 3rd character beginning from 0
print (x[2])
# Prints 7th character
print (x[6])
# Prints 3rd character from the rear beginning from -1
print (x[-3])
# Length of string is 10 so it is out of bound
print (x[15])
输出:
Traceback (most recent call last):
File "8a33ebbf716678c881331d75e0b85fe6.py", line 15, in
print x[15]
IndexError: string index out of range
e
a
o
切片
要从整个字符串中提取子字符串,我们使用如下语法
string_name[beginning: end : step]
- begin 表示字符串的起始索引
- end 表示不包含的字符串的结束索引
- step 表示两个词之间的距离。
注意:我们也可以使用 begin 和 only 对字符串进行切片,并且steps 是可选的。
例子:
# A python program to illustrate
# print substrings of a string
x = "Welcome to GeeksforGeeks"
# Prints substring from 2nd to 5th character
print (x[2:5])
# Prints substring stepping up 2nd character
# from 4th to 10th character
print (x[4:10:2])
# Prints 3rd character from rear from 3 to 5
print (x[-5:-3])
输出:
lco
oet
Ge