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


当前回答

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 '


其他回答

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

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

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

new_sub_string = myString[2:]

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

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 '


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'

也许我错过了,但我在这页上找不到原始问题的完整答案,因为这里没有进一步讨论变量。所以我不得不继续寻找。

既然我还不能发表评论,让我在这里补充我的结论。我确信在访问此页面时,我不是唯一对此感兴趣的人:

 >>>myString = 'Hello World'
 >>>end = 5

 >>>myString[2:end]
 'llo'

如果你离开第一部分,你会得到

 >>>myString[:end]
 'Hello' 

如果将:放在中间,则会得到最简单的子字符串,即第5个字符(计数以0开头,因此在本例中为空):

 >>>myString[end]
 ' '