我想从第三个字符到字符串末尾获得一个新字符串,例如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 '
其他回答
除了“结束”,你就在那里。这叫做切片表示法。您的示例应为:
new_sub_string = myString[2:]
如果省略了第二个参数,则它隐式地是字符串的结尾。
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]
它有效-不会引发错误,也不会出现默认的“字符串填充”。
>>> x = "Hello World!"
>>> x[2:]
'llo World!'
>>> x[:2]
'He'
>>> x[:-2]
'Hello Worl'
>>> x[-2:]
'd!'
>>> x[2:-2]
'llo Worl'
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")