我想从第三个字符到字符串末尾获得一个新字符串,例如myString[2:end]。如果省略第二部分意味着“到结尾”,如果省略第一部分,它是否从头开始?
当前回答
>>> x = "Hello World!"
>>> x[2:]
'llo World!'
>>> x[:2]
'He'
>>> x[:-2]
'Hello Worl'
>>> x[-2:]
'd!'
>>> x[2:-2]
'llo Worl'
Python将这一概念称为“切片”,它不仅仅适用于字符串。请在此处查看全面介绍。
其他回答
a="Helloo"
print(a[:-1])
在上面的代码中,[:-1]声明从开始打印到最大限制-1。
输出:
>>> Hello
注意:这里a[:-1]也与a[0:-1]和a[0:len(a)-1]相同
a="I Am Siva"
print(a[2:])
输出:
>>> Am Siva
在上面的代码中,[2:]声明从索引2打印到最后一个元素。
请记住,如果您将打印字符串的最大限制设置为(x),那么它将打印字符串直到(x-1),并且还请记住列表或字符串的索引将始终从0开始。
text = "StackOverflow"
#using python slicing, you can get different subsets of the above string
#reverse of the string
text[::-1] # 'wolfrevOkcatS'
#fist five characters
text[:5] # Stack'
#last five characters
text[-5:] # 'rflow'
#3rd character to the fifth character
text[2:5] # 'rflow'
#characters at even positions
text[1::2] # 'tcOefo'
使用硬编码索引本身可能会一团糟。
为了避免这种情况,Python提供了一个内置的对象slice()。
string = "my company has 1000$ on profit, but I lost 500$ gambling."
如果我们想知道我还剩多少钱。
正常溶液:
final = int(string[15:19]) - int(string[43:46])
print(final)
>>>500
使用切片:
EARNINGS = slice(15, 19)
LOSSES = slice(43, 46)
final = int(string[EARNINGS]) - int(string[LOSSES])
print(final)
>>>500
使用切片可以获得可读性。
str1='There you are'
>>> str1[:]
'There you are'
>>> str1[1:]
'here you are'
#To print alternate characters skipping one element in between
>>> str1[::2]
'Teeyuae'
#To print last element of last two elements
>>> str1[:-2:-1]
'e'
#Similarly
>>> str1[:-2:-1]
'e'
#Using slice datatype
>>> str1='There you are'
>>> s1=slice(2,6)
>>> str1[s1]
'ere '
Subs()通常(即PHP和Perl)是这样工作的:
s = Substr(s, beginning, LENGTH)
所以参数是开始和长度。
但Python的行为不同;它需要开头和END(!)之后的一个。初学者很难发现这一点。因此,Substr(s,begin,LENGTH)的正确替换为
s = s[ beginning : beginning + LENGTH]