字符串是字符的有序集合,可以通过其位置来获得具体的元素。在python中,字符串中的字符是通过索引来提取的,索引从0开始。
python可以取负值,表示从末尾提取,最后一个为-1,倒数第二个为-2,即程序认为可以从结束处反向计数。

>>> s1="hello"
>>> s2="hello world"
>>> s1 in s2
True
>>> w in s2
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
w in s2
NameError: name 'w' is not defined
>>> "w" in s2
True
>>> "w" in s1
False
>>> s1==s2
False
>>> if s1 != s2:print('no')
no
>>> s2
'hello world'
>>> s1
'hello'
>>> print(s2[0])
h
>>> print(s2[-1])
d
>>> print(s2[0:5])
hello
>>> print(s2[0:4])
hell
>>> print(s2[:5])
hello
>>> print(s2[6:])
world
>>> print(s2[-5])
w
>>> print(s2[-5:])
world
>>> print([s2])
['hello world']
>>> print(s2[:])
hello world
>>> print(s2[::2])
hlowrd
>>> print(s2[1:7:2])
el
例如:
string = "what the fuck^_^"
可以使用分片符和步长符:来给字符串进行分片和定义步长

string = "what the fuck^_^" #默认返回全部 print string[:] #返回1到9结果 print string[1:9] #返回1到9结果,步长为1 print string[1:9:] #返回1到9结果,步长为2 print string[1:9:2] #返回1到9结果,步长为-1 print string[1:9:-1] #转置 print string[::-1]

结果如下:

这里发现
#返回1到9结果,步长为-1 print string[1:9:-1]
没有输出1到9的逆序,这时将string[1:9]看成第一个字符串,然后转置就行了
#返回1到9结果,步长为-1 print string[1:9][::-1]
用这个方法判断某个字符串的子串是否为回文串就很有灵性了
本文深入讲解Python中字符串的索引、切片、步长等操作方法,演示如何判断子串及回文串,并提供丰富的代码实例。
933

被折叠的 条评论
为什么被折叠?



