简体   繁体   中英

If first or last character from string is $ remove it in python

table_name='Customer$'
if table_name.startswith('$'):
    table_name=table_name[1:]
if table_name.endswith('$'):
    table_name=table_name[:-1]

I tried with the above code it gives me correct result as

 Customer

Is there any optimized way of doing it? please reply

Use .strip() :

table_name = '$Customer$'.strip('$')

This will remove all $ s from the start and end and do nothing if there aren't dollars surrounding the string.

'$Customer$'.strip('$')

strip() method removes any leading (spaces at the beginning) and trailing (spaces at the end) characters (space is the default leading character to remove). By default trailing and leading spaces are removed. If an argument of character/s should be removed has been passed, then that character/s will be removed from leading and trailing poistions

just use .strip() it works like trim()

table_name = '$Cu$$stomer$'
ans = table_name.strip('$')
print(ans)  # output Cu$$stomer

The strip() method returns a copy of the string by removing both the leading and the trailing characters (based on the string argument passed).

you can learn more about strip() from here: https://www.programiz.com/python-programming/methods/string/strip

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