简体   繁体   中英

Python/Regex - Replace by pattern only at the end of string

I need to replace every parenthesis at the end of a string. I use this code:

a = '1 (FR) Product (IT, DE, ES)'
b = re.sub(r' \((.*?)\)',r'', a)

But this will replace every parenthesis in my string. How do I tell python to replace it only if the pattern is at the end of the string?

Capture everything but ( before ) and end of string identifier $ :

>>> import re
>>> a = '1 (FR) Product (IT, DE, ES)'
>>> re.sub(r'\(([^(]*\))$', '', a)
'1 (FR) Product '

if a[-1] == ")" a = a[:-2]将起作用

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