简体   繁体   中英

How to remove square brackets from string?

I want to remove the both of the square brackets in the output of my code.

My code:

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]

Example output of code:

[[12.97], [13.13]]

Desired output of code:

12.97, 13.13

using str.replace method

    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)

output

12.97, 13.13

or using regex

import re

al = [1, 2, [5, 6], 8, 9]

z = re.sub(r'\[', '', str(al)) 
y = re.sub(r'\]','', z) 

print(y)

ouput

1, 2, 5, 6, 8, 9

.join() also help to join list of list like this way:

output = [[12.97], [13.13]]
result = '\n'.join(','.join(map(str, row)) for row in output)
print(result)

output :

12.97
13.13

also try this :

result2 = ', '.join(','.join(map(str, row)) for row in output)
print(result2)

output:

 12.97, 13.13

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM