只有一次我有一個字符串的結構是這樣的:如何通過標籤來分割字符串,但每次發生
"I\thave\ta\t\tstring"
而且爲了通過選項卡拆分我用這個方法:
text = [splits for splits in row.split("\t") if splits is not ""]
現在這方法刪除字符串中的所有選項卡,但我希望它只刪除一個單詞後第一個出現的選項卡,因此它最終將如下所示:
"Ihavea\tstring"
有沒有辦法做到這一點?
只有一次我有一個字符串的結構是這樣的:如何通過標籤來分割字符串,但每次發生
"I\thave\ta\t\tstring"
而且爲了通過選項卡拆分我用這個方法:
text = [splits for splits in row.split("\t") if splits is not ""]
現在這方法刪除字符串中的所有選項卡,但我希望它只刪除一個單詞後第一個出現的選項卡,因此它最終將如下所示:
"Ihavea\tstring"
有沒有辦法做到這一點?
背後斷言負看看使用re.split
應該做的:
import re
s = ''.join(re.split(r'(?<!\t)\t', row))
print(s)
# 'Ihavea\tstring'
斷言(?<!\t)
防止在其上之前由另一\t
一個\t
分裂。
您可以使用re.sub
如果你實際上並不需要從拆分項目:
s = re.sub(r'(?<!\t)\t', '', row)
print(s)
# 'Ihavea\tstring'
爲了簡單起見,你可以使用re.split
from re import split
text = "I\thave\ta\t\tstring"
split_string = split(r'\t+', text) #Gives ['I', 'have', 'a', 'string']
正則表達式r'\t+'
基本上只是集團所有連續標籤在一起。
請記住,這是嚴格分割字符串。你可以很容易地用'「」join加入(split_string)' –
我承認@MosesKoledoye有一個更好的答案,因爲我的答案只是刪除所有的標籤將分裂他們,他將保留一個,如果有多個。 –
列表理解也是很長的路要走,如果你想避免導入re模塊:
row = "I\thave\ta\t\tstring"
text = [splits if splits else "\t" for splits in row.split("\t")]
"".join(text)
#'Ihavea\tstring'
空字符串是在布爾上下文假和空列表元素會爲每個連續的分裂而產生-char(在這種情況下爲「\ t」)
完美地工作,謝謝! –