如何从字符串中删除方括号?

2024-05-14 03:43:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想删除代码输出中的两个方括号

我的代码:

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

Tags: 代码inhttpsforgetwwwrequestsselection
3条回答

.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

使用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

相关问题 更多 >