python 字符串 分片索引

字符串是字符的有序集合,可以通过其位置来获得具体的元素。在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]

 

 

用这个方法判断某个字符串的子串是否为回文串就很有灵性了

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值