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.

3rd Jun 2021, 4:56 PM
David Holmes Ng'andu
David Holmes Ng'andu - avatar
6 Respostas
+ 4
Just add a space to your pattern so they aren't removed. r'[^a-zA-Z ]'
3rd Jun 2021, 6:53 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
???? Why down vote I just told you your problem lol
3rd Jun 2021, 6:38 PM
Roderick Davis
Roderick Davis - avatar
+ 1
3rd Jun 2021, 7:01 PM
David Holmes Ng'andu
David Holmes Ng'andu - avatar
+ 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 ;)
3rd Jun 2021, 7:22 PM
visph
visph - avatar
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
3rd Jun 2021, 6:58 PM
David Holmes Ng'andu
David Holmes Ng'andu - avatar
- 1
Becuase spaces arent letters so they are removed
3rd Jun 2021, 5:39 PM
Roderick Davis
Roderick Davis - avatar