How can I check if a string contains only printable characters in Python?
Richard W
To check if a string contains only printable characters in Python, you can utilize thestring module and thestring.printable constant. Thestring.printable constant contains all the printable characters in ASCII, including digits, letters, punctuation marks, and whitespace.
Here's an example of how you can perform this check:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import string
def contains_only_printable(string):
for char in string:
if char not in string.printable:
return False
return True
# Usage:
input_string = input("Enter a string: ")
if contains_only_printable(input_string):
print("The string contains only printable characters.")
else:
print("The string contains non-printable characters.")
In the above code, thecontains_only_printable() function takes astring parameter representing the input string to check. It iterates through each character in the string using afor