0

symbols coad coach

import string import re text = input() alphanumeric_chars = string.ascii_letters + string.digits for letters in text: if letters not in alphanumeric_chars: found_chars += letters for char in found_chars: text = text.replace(char, "") new_text = "" found_number = False #flag to track for i in range(len(text)): if i > 0 and (text[i].isupper() or (not found_number and text[i].isdigit())): new_text += " " + text[i] if text[i].isdigit(): found_number = True else: new_text += text[i] print(new_text) # Output: hello World 123 It works on all but test case 3 and 4. Can anyone help me with this

24th Dec 2024, 6:59 PM
Joakim Lindstrom
Joakim Lindstrom - avatar
1 Resposta
+ 3
✳️ you have to define found_chars first before using it in the for loop. You also don't need the bottom part of your code if you just include string.whitespace in alphanumeric_chars. import string text = input() alphanumeric_chars = string.ascii_letters + string.digits + string.whitespace found_chars = "" for letters in text: if letters not in alphanumeric_chars: found_chars += letters for char in found_chars: text = text.replace(char, "") print(text) ✳️ But your solution is still too complicated. You can simplify it to: import string text = input() valid_chars = string.ascii_letters + string.digits + string.whitespace result = "" for letter in text: if letter in valid_chars: result += letter print(result) ✳️ Or use isalnum() and isspace() to build your string. Then you don't have to import any module at all. text = input() result = "" for letter in text: if letter.isalnum() or letter.isspace(): result += letter print(result)
25th Dec 2024, 12:50 AM
Bob_Li
Bob_Li - avatar