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


其他回答

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

s = Substr(s, beginning, LENGTH)

所以参数是开始和长度。

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

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

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

嗯,我遇到了一个需要将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

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

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