我想从第三个字符到字符串末尾获得一个新字符串,例如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 '


其他回答

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 '


如果myString包含一个从偏移量6开始且长度为9的帐号,则可以通过以下方式提取帐号:acct=myString[6:][:9]。

如果OP接受这一点,他们可能希望以实验的方式,

myString[2:][:999999]

它有效-不会引发错误,也不会出现默认的“字符串填充”。

Subs()通常(即PHP和Perl)是这样工作的:

s = Substr(s, beginning, LENGTH)

所以参数是开始和长度。

但Python的行为不同;它需要开头和END(!)之后的一个。初学者很难发现这一点。因此,Substr(s,begin,LENGTH)的正确替换为

s = s[ beginning : beginning + LENGTH]
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'

我想在讨论中补充两点:

您可以在空白处使用None来指定“从开始”或“到结束”:“abcde”[2:无]==“abcde'[2:]==”cde“这在函数中特别有用,因为在函数中不能提供空格作为参数:def子字符串(s,start,end):“”“删除开头和结尾的“start”字符字符串“s”结尾的字符。示例-------->>>子字符串('abcde',0,3)“abc”>>>子字符串('abcde',1,无)“bcdedit”"""return s[开始:结束]Python具有切片对象:idx=切片(2,无)'abcde'[idx]=='abcde'[2:]=='cde'