2013-05-14 79 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' 
相關問題