How to rermove non-alphanumeric characters at the beginning or end of a string

后端 未结 5 1398
故里飘歌
故里飘歌 2020-12-07 03:27

I have a list with elements that have unnecessary (non-alphanumeric) characters at the beginning or end of each string.

Ex.

\'cats--\'
5条回答
  •  难免孤独
    2020-12-07 03:32

    I believe that this is the shortest non-regex solution:

    text = "`23`12foo--=+"
    
    while len(text) > 0 and not text[0].isalnum():
        text = text[1:]
    while len(text) > 0 and not text[-1].isalnum():
        text = text[:-1]
    
    print text
    

提交回复
热议问题