Detect Whether a Python String Is a Number or a Letter [Duplicate]

Detect Whether a Python String Is a Number or a Letter [Duplicate]

How can I detect either numbers or letters in a string? I am aware you use the ASCII codes, but what functions take advantage of them?

2

2 Answers

Check if string is nonnegative digit (integer) and alphabet

You may use str.isdigit() and str.isalpha() to check whether a given string is a nonnegative integer (0 or greater) and alphabetical character, respectively.

Sample Results:

# For alphabet
>>> 'A'.isdigit()
False
>>> 'A'.isalpha()
True

# For digit
>>> '1'.isdigit()
True
>>> '1'.isalpha()
False
Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.