Create a list of characters that are digits from a string


This Python code takes a string and creates a new list called digits using a list comprehension. The new list contains only the digits from the original string. Here's how the code works:

  • string = "12345Hello67890": This line initializes a variable named string and assigns it a string containing a mix of digits and non-digit characters.
  • digits = [char for char in string if char.isdigit()]: This line of code initializes a variable named digits and assigns it the result of a list comprehension.
    • for char in string: This part sets up a loop that iterates through each character char in the string.
    • char.isdigit(): For each character in the string, this expression checks if the character is a digit using the isdigit() method, which returns True if the character is a digit and False otherwise.
    • [char for char in string if char.isdigit()]: This is the list comprehension itself. It iterates through the characters in the string, includes only the characters that are digits in the new list.
  • print(string): This line of code prints the original string to the console.
  • print(digits): This line of code prints the digits list (which contains the digit characters) to the console.

Source Code

string = "12345Hello67890"
digits = [char for char in string if char.isdigit()]
print(string)
print(digits)

Output

12345Hello67890
['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']

Example Programs