[英]How to remove brackets from python string?
我從標題中知道您可能認為這是重復的,但事實並非如此。
for id,row in enumerate(rows):
columns = row.findall("td")
teamName = columns[0].find("a").text, # Lag
playedGames = columns[1].text, # S
wins = columns[2].text,
draw = columns[3].text,
lost = columns[4].text,
dif = columns[6].text, # GM-IM
points = columns[7].text, # P - last column
dict[divisionName].update({id :{"teamName":teamName, "playedGames":playedGames, "wins":wins, "draw":draw, "lost":lost, "dif":dif, "points":points }})
這就是我的 Python 代碼的樣子。 大部分代碼已被刪除,但基本上我是從網站中提取一些信息。 我將信息保存為字典。 當我打印字典時,每個值都有一個括號 ["blbal"],這會導致我的 Iphone 應用程序出現問題。 我知道我可以將變量轉換為字符串,但我想知道是否有辦法將信息直接作為字符串獲取。
看起來您在列表中有一個字符串:
["blbal"]
要獲取字符串,只需 index l = ["blbal"]
print(l[0]) -> "blbal"
。
如果它是一個字符串,則使用str.strip
'["blbal"]'.strip("[]")
或 slicing '["blbal"]'[1:-1]
如果它們總是存在。
您也可以replace
為只用空字符串替換您不想要的文本/符號。
text = ["blbal","test"]
strippedText = str(text).replace('[','').replace(']','').replace('\'','').replace('\"','')
print(strippedText)
import re
text = "some (string) [another string] in brackets"
re.sub("\(.*?\)", "", text)
# some in brackets
# works for () and will work for [] if you replace () with [].
\(.*?\)
格式匹配括號,其中包含一些未指定長度的文本。 \[.*?\]
格式也匹配方括號,括號內有一些文本。
輸出將不包含括號和其中的文本。
如果您只想匹配方括號,請將方括號替換為選擇的括號,反之亦然。
要一次性匹配()
和[]
括號,請使用此格式(\(.*?\)|\[.*?\]:)
將兩個模式與|
特點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.