'Python ignore punctuation and white space

string = "Python, program!"

result = []
for x in string:
    if x not in result:
        result.append(x)
print(result)

This program makes it so if a repeat letter is used twice in a string, it'll appear only once in the list. In this case, the string "Python, program!" will appear as

['P', 'y', 't', 'h', 'o', 'n', ',', ' ', 'p', 'r', 'g', 'a', 'm', '!']

My question is, how do I make it so the program ignores punctuation such as ". , ; ? ! -", and also white spaces? So the final output would look like this instead:

['P', 'y', 't', 'h', 'o', 'n', 'p', 'r', 'g', 'a', 'm']



Solution 1:[1]

Just check if the string (letter) is alphanumeric using str.isalnum as an additional condition before appending the character to the list:

string = "Python, program!"

result = []
for x in string:
    if x.isalnum() and x not in result:
        result.append(x)
print(result)

Output:

['P', 'y', 't', 'h', 'o', 'n', 'p', 'r', 'g', 'a', 'm']

If you don't want numbers in your output, try str.isalpha() instead (returns True if the character is alphabetic).

Solution 2:[2]

You can filler them out using the string module. This build in library contains several constants that refer to collections of characters in order, like letters and whitespace.

import string

start = "Python, program!" #Can't name it string since that's the module's name
result = []
for x in start:
    if x not in result and (x in string.ascii_letters):
        result.append(x)

print(result)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 mousetail