Home > front end >  Python ignore punctuation and white space
Python ignore punctuation and white space

Time:03-05

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']

CodePudding user response:

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)

CodePudding user response:

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 not in result and x.isalnum():
        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).

  • Related