简体   繁体   中英

Remove a part of string from one character to another

For the following strings in a string:

User Input(id=2345) : Hello
User Input(id=9423924) : Hi!
User Input(id=233123) : How's it going

I want to remove the part in the brackets. to look something like:

User Input: Hello
User Input: Hi!
User Input: How's it going

I have tried the follow code:

import re
file = file1.read()
for line in file
   print(re.sub(r'\((.*?)\line)\+', '', line)) 

it gives me an error- any suggestions would be really helpful! Thank you

You can use regular expressions:

>>> s = 'User Input(id=2345) : Hello'
>>> import re
>>> re.sub(r'\(.+?\)', '', s)
'User Input : Hello'

This will not work super robustly for nested brackets, but for the input at hand, it should do just fine.

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