![](/img/trans.png)
[英]How to use regex re.compile Match() or findall() in list comprehension
[英]how to use the regex findall list
所以我是一名JS培訓生,在實習期間,有人要求我對python代碼做一些事情,但是我從未在Python上做過什么,所以我有點迷路了。我想將字符串分隔為differents塊。
這是我所擁有的:
buffer = """
#<start>
idothings
#</start>
#<params>
otherthings
#</params>
#<end>
andifinish
#</end>
我想要的是將這個字符串分為不同部分的正則表達式:
separatedString = [["#<start>,"idothings","#</start>"],["#<params>,"otherthings","#</params>"],["#<end>,"andifinish","#</end>"]]
我試圖做的是:
def getStructure(string):
separatedString = re.findall('(#<.+?>)(.|\n)+?(#<\/.+?>)', string)
return
但這給了我一個列表...我不明白如何在python中瀏覽列表...
[("#<start>", '\n', '#</start>'), ('#<azeaze>', '\n', '#</azeaze>'), ('#<sgdfs>', 'x', '#</sgdfs>')]
我試過了 :
print '\n'.join(["%s a %s et %s" %(p1,p2,p3) for p1, strings in separatedString ])
但它給我帶來了一個錯誤:“無法解開太多的價值”
有人可以告訴我我該怎么做嗎?
您的印刷聲明有誤。 試試這個
print '\n'.join(["%s a %s et %s" %(p1,p2,p3) for p1, p2, p3 in separatedString ])
您收到錯誤是因為,您試圖從具有三個元素的元組中獲取兩個值
for p1, strings in separatedString
在這里, separatedString
字符串在每個成員中都有3個元素
buffer = """#<start>
idothings
#</start>
#<params>
otherthings
#</params>
#<end>
andifinish
#</end>"""
spl = buffer.splitlines()
print([spl[i:i+3] for i in range(0,len(spl),3)])
[['#<start>', ' idothings', '#</start>'], ['#<params>', ' otherthings', '#</params>'], ['#<end>', ' andifinish', '#</end>']]
spl = buffer.splitlines()
sliced = [spl[i:i+3] for i in range(0,len(spl),3)]
for a,b,c in sliced:
print(a.strip(),b.strip(),c.striip())
('#<start>', 'idothings', '#</start>')
('#<params>', 'otherthings', '#</params>')
('#<end>', 'andifinish', '#</end>')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.