简体   繁体   中英

Remove specific brackets from string

I have a list of say:

(UH[0], UH[1], UH[2], UH[3].... )

I want to use re.sub to remove everything from each element of the list except the number so that it is

(0 , 1 , 2 , 3 .....)

I tried with:

re.sub ('[UH^[]]' ,'', each_element)

but it doesn't work.

re.findall might be an option too:

import re

string = 'UH[0], UH[1], UH[2], UH[3].... '
print(re.findall(r'\d+', string))

Output

['0', '1', '2', '3']

You can try to replace them like

In [1]: x = "UH[0], UH[1], UH[2], UH[3]"

In [2]: result = x.replace("[","").replace("]","").replace("UH", "")

In [3]: result
Out[3]: '0, 1, 2, 3'

Hope it helps.

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