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


其他回答

我想在讨论中补充两点:

您可以在空白处使用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'

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

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

这里似乎缺少一个示例:完整(浅)拷贝。

>>> x = "Hello World!"
>>> x
'Hello World!'
>>> x[:]
'Hello World!'
>>> x==x[:]
True
>>>

这是创建序列类型副本(而不是内部字符串)[:]的常见习惯用法。Shallow复制一个列表,请参阅Python列表切片语法,无明显原因。

我有一个更简单的解决方案,使用for循环来查找字符串中的给定子字符串。假设我们有两个字符串变量,

main_string = "lullaby"
match_string = "ll"

如果要检查主字符串中是否存在给定的匹配字符串,可以执行以下操作:,

match_string_len = len(match_string)
for index,value in enumerate(main_string):
    sub_string = main_string[index:match_string_len+index]
    if sub_string == match_string:
       print("match string found in main string")

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

s = Substr(s, beginning, LENGTH)

所以参数是开始和长度。

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

s = s[ beginning : beginning + LENGTH]