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
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.