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


当前回答

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'

其他回答

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

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

s = Substr(s, beginning, LENGTH)

所以参数是开始和长度。

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

s = s[ beginning : beginning + LENGTH]

使用硬编码索引本身可能会一团糟。

为了避免这种情况,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

使用切片可以获得可读性。

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'

我有一个更简单的解决方案,使用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")