check if string in python contains only letters and numbers

Python – Check If String Contains Only Letters and Numbers

In this tutorial, we will look at how to check if a string contains only letters and numbers in Python with the help of examples.

check if string in python contains only letters and numbers

You can use the string isalnum() function to check if a string contains only letters (that is, alphabets) and/or numbers in Python. The following is the syntax –

# check if string s contains only alphanumeric characters
s.isalnum()

It returns True if all the characters in the string are alphanumeric (containing only alphabets and/or numbers). If any of the characters is not alphanumeric, it returns False.

Let’s look at an example.

# create a string
s = "Bunny123"
# check if string contains only alphanumeric characters
print(s.isalnum())

Output:

True

We get True as the output. This is because all the characters in the string s above are either letters or numbers.

Let’s look at another example.

# create a string
s = "Bunny_123"
# check if string contains only alphanumeric characters
print(s.isalnum())

Output:

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

False

Here, we get False as the output. This is because not all characters in the string s above are alphanumeric. One of the characters in the string, “_” is neither an alphabet nor a digit.

For more on the string isalnum() function, refer to its documentation.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top