2013-05-14 49 views
2

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

例如:

找到2个逗号之间的字符串:

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 

然而我想知道是否有更简单的方法,或者可能只是简单的不同。谢谢!

回答

7

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

+0

三江源,我我知道我在做这件事:I – ReallyGoodPie 2013-05-14 13:19:05

+0

@ReallyGoodPie它可能会通过一个不包含任何逗号的字符串和一个包含单个逗号的字符串来运行,并检查结果是否如您期望的那样。 – 2013-05-14 13:49:25

+0

这就是我所期待的,并不完全是这样,但它对我所做的事很有用 – ReallyGoodPie 2013-05-14 13:57:43

1

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

实施例:

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

另一个选项是找到两个参考文献的索引时这些引用并不需要是相同的(如在两个逗号):

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' 
相关问题