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


当前回答

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

其他回答

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

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

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

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

new_sub_string = myString[2:]

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

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的字符串[开始:结束],我必须计算很多结束索引,所以更简单的方法是使用字符串[开始][:长度],这为我省去了很多麻烦。

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

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

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