Generate a set of characters that are digits from a string
This Python code uses a set comprehension to create a set named digits that contains all the unique digit characters from the input string. Here's how the code works:
- string = "12345Hello67890": This line initializes a string named string containing a mix of digits and non-digit characters.
- digits = {char for char in string if char.isdigit()}: This line initializes the set digits using a set comprehension.
- for char in string: This part of the code sets up a loop that iterates through each character in the string.
- {char.isdigit()}: For each character, this part includes the character in the digits set if it is a digit. The condition char.isdigit() checks whether the character is a digit or not.
- print(string): This line of code prints the original string to the console.
- print(digits) : This line of code prints the digits set to the console.
Source Code
string = "12345Hello67890"
digits = {char for char in string if char.isdigit()}
print(string)
print(digits)
Output
12345Hello67890
{'2', '8', '7', '3', '9', '0', '1', '5', '4', '6'}