How to locate digits and capital letters in a Python string

Viewed 58

Is there a way to locate capital letters and digits in a string?

Here is the code I have so far:

# Imports


import random

# Variables

my_score = 0
loop = True

# start

while loop == True:

  username = input("Enter your username")

  has_digit = False
  has_upper = False

I tried searching Google but I couldn't find anything that seems to work, any ideas?

4 Answers

You can use any() for this:

has_digit = any(c.isdigit() for c in username)
has_upper = any(c.isupper() for c in username)
import re

has_upper = True if re.search('[A-Z]', username) else False
has_digit = True if re.search('\d', username) else False

Use any, isdigit, and isupper:

>>> while True:
...     username = input("Enter your username")
...     if any(c.isdigit() for c in username):
...         print("there's a digit in that")
...     if any(c.isupper() for c in username):
...         print("there's a capital letter in that")
...
Enter your usernamebob
Enter your usernameBob
there's a capital letter in that
Enter your usernameBob123
there's a digit in that
there's a capital letter in that

If you want to get the number of each type of character, use sum instead of any:

>>> while True:
...     username = input("Enter your username: ")
...     print(f"There are {sum(c.isupper() for c in username)} capital letters in that.")
...     print(f"There are {sum(c.isdigit() for c in username)} digits in that.")
...
Enter your username: bob
There are 0 capital letters in that.
There are 0 digits in that.
Enter your username: Bob
There are 1 capital letters in that.
There are 0 digits in that.
Enter your username: Bob123
There are 1 capital letters in that.
There are 3 digits in that.

As the other answers suggest, you can use any() function to traverse the string and search for digits and specific characters. But to know if there is a numeric character or a digit in your string, .isalnum() results in an alternative that you can use in many string related problems:

username = input("Enter your username")
has_digit = username.isalnum()
has_upper = any(c.isupper() for c in username)
Related