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

时间:2013-05-14 13:15:32

标签: python string

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

例如:

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

Hello, This is the string I want, blabla

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

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

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

3 个答案:

答案 0 :(得分:8)

这是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'

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

>>> foo.split(',')[1].lstrip()
'this is the string I want'

通常有一种内置方法可用于Python中的简单方法:-)
有关详细信息,请查看Built-in Types - String methods

答案 1 :(得分:3)

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

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'

答案 2 :(得分:1)

我会使用re - 如果你希望开始/结束点不同,或者你想要更复杂的标准,这会更容易。

示例:

>>> import re
>>> s = "Hello, This is the string I want, blabla"
>>> re.search(',(.*?),', s).group(1)
' This is the string I want'
相关问题