Delete all not allowed characters..

Michal Bozon bozonm at vscht.cz
Thu Oct 25 11:42:36 EDT 2007


On Thu, 25 Oct 2007 07:52:36 -0700, Abandoned wrote:

> Hi..
> I want to delete all now allowed characters in my text.
> I use this function:
> 
> def clear(s1=""):
>     if s1:
>         allowed =
> [u'+',u'0',u'1',u'2',u'3',u'4',u'5',u'6',u'7',u'8',u'9',u' ', u'Ş',
> u'ş', u'Ö', u'ö', u'Ü', u'ü', u'Ç', u'ç', u'İ', u'ı', u'Ğ', u'ğ', 'A',
> 'C', 'B', 'E', 'D', 'G', 'F', 'I', 'H', 'K', 'J', 'M', 'L', 'O', 'N',
> 'Q', 'P', 'S', 'R', 'U', 'T', 'W', 'V', 'Y', 'X', 'Z', 'a', 'c', 'b',
> 'e', 'd', 'g', 'f', 'i', 'h', 'k', 'j', 'm', 'l', 'o', 'n', 'q', 'p',
> 's', 'r', 'u', 't', 'w', 'v', 'y', 'x', 'z']
>         s1 = "".join(ch for ch in s1 if ch in allowed)
>         return s1
> 
> ....And my problem this function replace the character to "" but i
> want to " "
> for example:
> input: Exam%^^ple
> output: Exam   ple
> I want to this output but in my code output "Example"
> How can i do quickly because the text is very long..

the list comprehension does not allow "else",
but it can be used in a similar form:

s2 = ""
for ch in s1:
    s2 += ch if ch in allowed else " "

(maybe this could be written more nicely)



More information about the Python-list mailing list