Removing any single letter on a string in python

前端 未结 5 1729
萌比男神i
萌比男神i 2021-01-12 18:35

I would like to remove any single letter from a string in python.

For example:

input: \'z 23rwqw a 34qf34 h 343fsdfd\'
output: \'23rwqw 34qf34 343fsd         


        
5条回答
  •  暖寄归人
    2021-01-12 19:13

    I had a similar issue and came up with the following regex solution:

    import re
    pattern = r"((?<=^)|(?<= )).((?=$)|(?= ))"
    text = "z 23rwqw a 34qf34 h 343fsdfd"
    print(re.sub("\s+", " ", re.sub(pattern, '', text).strip()))
    #23rwqw 34qf34 343fsdfd
    

    Explanation

    • (?<=^) and (?<= ) are look-behinds for start of string and space, respectively. Match either of these conditions using | (or).
    • . matches any single character
    • ((?=$)|(?= )) is similar to the first bullet point, except it's a look-ahead for either the end of the string or a space.

    Finally call re.sub("\s+", " ", my_string) to condense multiple spaces with a single space.

提交回复
热议问题