我想从第三个字符到字符串末尾获得一个新字符串,例如myString[2:end]。如果省略第二部分意味着“到结尾”,如果省略第一部分,它是否从头开始?


当前回答

除了“结束”,你就在那里。这叫做切片表示法。您的示例应为:

new_sub_string = myString[2:]

如果省略了第二个参数,则它隐式地是字符串的结尾。

其他回答

>>> x = "Hello World!"
>>> x[2:]
'llo World!'
>>> x[:2]
'He'
>>> x[:-2]
'Hello Worl'
>>> x[-2:]
'd!'
>>> x[2:-2]
'llo Worl'

Python将这一概念称为“切片”,它不仅仅适用于字符串。请在此处查看全面介绍。

实现这一点的常见方法是通过字符串切片。

MyString[a:b]提供了从索引a到(b-1)的子字符串。

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 '


嗯,我遇到了一个需要将PHP脚本转换为Python的情况,它有许多substr(字符串、开头、长度)的用法。如果我选择Python的字符串[开始:结束],我必须计算很多结束索引,所以更简单的方法是使用字符串[开始][:长度],这为我省去了很多麻烦。

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'