简体   繁体   中英

How do I remove a specific part of a string?

I'd like to remove a specific part of a string within a pandas df. More precisely, I want the script to remove everything within '(' and ')'. Example:

'3453(s656)s(657)' -script-> '3453s'

Is there an easy implemented python function or need I to script it by my self? Thanks for any help!

You could use str.replace . Here's an example dataframe:

df = pd.DataFrame({'col1':['3453(s656)s(657)', 'another(---)string']})

df['col1'] = df.col1.str.replace(r'(\(.*?\))', '')
        col1
0          3453s
1  anotherstring

you could implement a simple python function to do just the following as:

def speclace(a)
    x=""
    s=0
    for i in a:
        if i=='(':
            s=1
        elif i==')':
            s=0
        elif s==0:
            x+=i
return x

<-- Upvote if helpful -->

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