C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: The string.punctuation values do not include Unicode symbols or whitespace characters.
Python program that uses string.punctuation
import string
# Display punctuation.
for c in string.punctuation:
print("[" + c + "]")
Output
[!]
["]
[#]
[$]
[%]
[&]
[']
[(]
[)]
[*]
[+]
[,]
[-]
[.]
[/]
[:]
[;]
[<]
[=]
[>]
[?]
[@]
[[]
[\]
[]]
[^]
[_]
[`]
[{]
[|]
[}]
[~]
Python program that tests for punctuation
import string
# An input string.
name = "hey, my friend!"
for c in name:
# See if the char is punctuation.
if c in string.punctuation:
print("Punctuation: " + c)
Output
Punctuation: ,
Punctuation: !
Note: We add each character to our result that is not punctuation. Spaces (which are not punctuation) are kept.
Python program that removes punctuation from string
import string
def remove_punctuation(value):
result = ""
for c in value:
# If char is not punctuation, add it to the result.
if c not in string.punctuation:
result += c
return result
# Test our method.
temp = "hello, friend!... welcome."
print(temp)
print(remove_punctuation(temp))
Output
hello, friend!... welcome.
hello friend welcome
Tip: Instead of testing constant strings with "in," consider using methods like isspace().
Python program that uses string.whitespace
import string
print(" " in string.whitespace)
print("\n" in string.whitespace)
print("X" in string.whitespace)
Output
True
True
False