I have strings, and I need to remove only numbers inside brackets (remove brackets too) from this:
str = "1.25 (10), 1.5 (148), 1.25 (24)"
to this:
"1.25, 1.5, 1.25"
Try:
import re
x = "1.25 (10), 1.5 (148), 1.25 (24)"
x=re.sub(r'\s*\(\d+\)\s*', '',x)
Outputs:
>>> x
1.25, 1.5, 1.25
Use:
str = "1.25 (10), 1.5 (148), 1.25 (24)"
a=[i for i in str.split(" ") if ("(" not in i)]
str=",".join(a)
print(str)
Answer:
1.25,1.5,1.25
welcome to Stack Overflow
You can use regex like this:
import re
str = "1.25 (10), 1.5 (148), 1.25 (24)"
new_str = re.sub("\s\([0-9.]+\)", "", str)
The regex command looks for patterns starting with a space followed by a number inside a bracket and replaces it with an empty string.
I tried by getting the brackets and items inside the it and thereafter remove it
import re
string = "1.25 (10), 1.5 (148), 1.25 (24)"
txt = string.split(',')
clear = ''
for i in txt:
clear += re.sub('\(.*\)', '', i)
print(clear.replace(' ', ', '))
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.