The isascii()
method is a built-in method in Python that checks whether all the characters in a string are ASCII characters or not.
Syntax
The syntax of the isascii()
method is as follows:
string.isascii()
Here, string
is the string that we want to check for ASCII characters.
Return Value
The isascii()
method returns True
if all the characters in the string are ASCII characters, otherwise it returns False
.
Examples
Here are three different examples of how to use the isascii()
method in Python:
Example 1: Checking if a String Contains ASCII Characters
The following example demonstrates how to use the isascii()
method to check if a string contains ASCII characters:
string = "Hello World!" result = string.isascii() print(result)
Output:
True
In this example, we define a string “Hello World!” and use the isascii()
method to check whether all the characters in the string are ASCII characters. Since all the characters in the string are ASCII characters, the method returns True
.
Example 2: Checking if a String Contains Non-ASCII Characters
The following example demonstrates how to use the isascii()
method to check if a string contains non-ASCII characters:
string = "你好世界" result = string.isascii() print(result)
Output:
False
In this example, we define a string “你好世界” (which means “Hello World!” in Chinese) and use the isascii()
method to check whether all the characters in the string are ASCII characters. Since the string contains non-ASCII characters, the method returns False
.
Example 3: Using the isascii() Method in a Loop
The following example demonstrates how to use the isascii()
method in a loop:
strings = ["Hello World!", "你好世界"] for string in strings: result = string.isascii() print(f"{string}: {result}")
Output:
Hello World!: True 你好世界: False
In this example, we define a list of strings and use a loop to iterate over each string in the list. We use the isascii()
method to check whether all the characters in each string are ASCII characters. The output shows the result of the method for each string in the list.
Use Cases
The isascii()
method can be useful in a variety of scenarios, such as:
- Checking whether user input contains non-ASCII characters before processing the input
- Validating text files to ensure that they only contain ASCII characters
- Ensuring that strings used in a certain context only contain ASCII characters