在两点之间找到字符串的最佳方法

Rea*_*Pie 3 python string

我知道这是相当基本的,但我想知道在两个引用点之间找到字符串的最佳方法是什么.

例如:

在两个逗号之间找到字符串:

Hello, This is the string I want, blabla
Run Code Online (Sandbox Code Playgroud)

我最初的想法是创建一个列表,让它做这样的事情:

stringtext= []
commacount = 0
word=""
for i in "Hello, This is the string I want, blabla":
    if i == "," and commacount != 1:
        commacount = 1
    elif i == "," and commacount == 1:
        commacount = 0
    if commacount == 1:
        stringtext.append(i)

print stringtext
for e in stringtext:
    word += str(e)

print word
Run Code Online (Sandbox Code Playgroud)

然而,我想知道是否有一种更简单的方法,或者可能只是一种简单的方式.谢谢!

tim*_*mss 9

str.split(delimiter)是为了什么.
它返回一个列表,您可以执行[1]或迭代.

>>> foo = "Hello, this is the string I want, blabla"
>>> foo.split(',')
['Hello', ' this is the string I want', ' blabla']
>>> foo.split(',')[1]
' this is the string I want'
Run Code Online (Sandbox Code Playgroud)

如果你想摆脱你可以使用的领先空间str.lstrip(),或者str.strip()也想删除尾随:

>>> foo.split(',')[1].lstrip()
'this is the string I want'
Run Code Online (Sandbox Code Playgroud)

通常有一种内置方法可用于Python中的简单方法:-)
有关更多信息,请查看内置类型 - 字符串方法


zen*_*poy 5

另一种选择是在两个引用不需要相同时找到两个引用的索引(如两个逗号):

a = "Hello, This is the string I want, blabla"
i = a.find(",") + 1
j = a.find(",",i)
a[i:j]
>>> ' This is the string I want'
Run Code Online (Sandbox Code Playgroud)