0
How to make this have a space between words
import re new_str = "" user_str = input() pattern = r'[^a-zA-Z]' new_str = re.sub(pattern, '', user_str) print(new_str[::-1]) This code takes a string from user, matches anything that isn't a letter, replaces it with an empty string, reverse, then prints it. Problem is, it doesn't add a space between words, but meanwhile it works well for a two word sentence.
6 Respostas
+ 4
Just add a space to your pattern so they aren't removed.
r'[^a-zA-Z ]'
+ 1
???? Why down vote I just told you your problem lol
+ 1
ChaoticDawg thanks
+ 1
if you add a space ' ' that will prevent removing only this specific space... if you want to add any kind of spaces (common ascii one, but also tabulations, new lines, non-breaking space, special unicode spaces of different widths...), you should use the '\s' (it's counterpart is '\S' wich means anything that is not a space):
pattern = r'[^a-bA-B\s]'
here the r prepending the string is useful, as you use backslash to escape the s in the regexp, but not in the string ;P
without, you need to escape it as well:
pattern = '[^a-bA-B\\s]'
and your pattern start to become less readable ;)
0
Roderick Davis i already knew the problem, now i have tried to dissolve it but i failed that's why i posted so you guys could help me out
- 1
Becuase spaces arent letters so they are removed