TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to PYTHON

Python isalnum: String Is Alphanumeric

Use the isalnum method to see whether a string contains only letters and digits.
Isalnum. Sometimes we want to ensure a string contains not punctuation or other whitespace. We want to see if the string contains just letters and digits.
With isalnum, we have a method that loops over the characters in the string. If any whitespace, punctuation, or other weird characters are found, it returns false.
An example. Here we see a program that uses isalnum. We can call isalnum() on a string instance, or use str.isanum and pass the string as the argument.

Tests: We have 7 strings in our tests list. Some have spaces, punctuation, and one is an empty string.

Strings

Result: The only strings that cause isalnum to return true are the ones with no whitespace or punctuation (and at least 1 character).

Python program that uses isalnum method tests = [] tests.append("The Dev Codes") tests.append("DotNetPerls") tests.append("Dot_Net_Perls") tests.append("Dot0123") tests.append("dotnetCodex") tests.append("123") tests.append("") for test in tests: # Test each string for alphanumeric status with isalnum. if test.isalnum(): print("isalnum: [", test, "]") else: print("false: [", test, "]") Output false: [ The Dev Codes ] isalnum: [ DotNetPerls ] false: [ Dot_Net_Perls ] isalnum: [ Dot0123 ] isalnum: [ dotnetCodex ] isalnum: [ 123 ] false: [ ]
A useful method. Often we want to validate strings before putting them into a dictionary or list. Isalnum is a good method to remember—it is easier than trying to write a similar method.DictionaryList
A review. When possible, methods like isalnum() from the standard library should be reused. They do not need testing—they are convenient and easy to understand.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf