Search code examples
pythonstringtrim

trim string to special charater


I have some string in the data frame look like these 'Temp (°C)','Dew Point Temp (°C)','Rel Hum (%)','Wind Dir (10s deg)'.

How can I trim the the part in the parenthesis and leave only "Temp', 'Dow Point Temp', "Rel Hum', 'Wind Dir'?

Please note I need to deal with special character like 'Â' or other special characters.


Solution

  • A very simple way to do it would be splitting on the first space-open parentheses ( combo like this

    a = 'Temp (°C)','Dew Point Temp (°C)','Rel Hum (%)','Wind Dir (10s deg)', 'column without units'
    
    [i.split(' (')[0] if ' (' in i else i for i in a]
    

    which produces

    ['Temp', 'Dew Point Temp', 'Rel Hum', 'Wind Dir', 'column without units']
    

    Note that I have included the if statement in the list comprehension to take care of names which don't contain any parentheses.