[英]How to remove square brackets from string?
我想刪除代碼輸出中的兩個方括號。
我的代碼:
request2 = requests.get('https://www.punters.com.au/api/web/public/Odds/getOddsComparisonCacheable/?allowGet=true&APIKey=65d5a3e79fcd603b3845f0dc7c2437f0&eventId=1045618&betType=FixedWin', headers={'User-Agent': 'Mozilla/5.0'})
json2 = request2.json()
for selection in json2['selections']:
for fluc in selection['flucs'][0]:
flucs1 = ast.literal_eval(selection['flucs'])
flucs2 = flucs1[-2:]
flucs3 = [[x[1]] for x in flucs2]
代碼輸出示例:
[[12.97], [13.13]]
所需的代碼輸出:
12.97, 13.13
使用 str.replace 方法
n = [[12.97], [13.13]]
m = str(n)[1:-1] # convert list into str to be able to use str.replace method
z = m.replace('[', '', 3)
y = z.replace(']', '', 3)
print(y)
輸出
12.97, 13.13
或使用正則表達式
import re
al = [1, 2, [5, 6], 8, 9]
z = re.sub(r'\[', '', str(al))
y = re.sub(r'\]','', z)
print(y)
輸出
1, 2, 5, 6, 8, 9
.join()
也有助於像這樣加入列表列表:
output = [[12.97], [13.13]]
result = '\n'.join(','.join(map(str, row)) for row in output)
print(result)
輸出 :
12.97
13.13
也試試這個:
result2 = ', '.join(','.join(map(str, row)) for row in output)
print(result2)
輸出:
12.97, 13.13
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.