Generate a list of characters from a string


This Python code creates a list called chars using a list comprehension to extract alphabetic characters from the given string "Hello, world!". Here's how the code works:

  • string = "Hello, world!": This line initializes a variable named string and assigns it the value "Hello, world!", which is a string containing letters, spaces, and punctuation.
  • chars = [char for char in string if char.isalpha()]: This line of code initializes a variable named chars 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.
    • if char.isalpha(): This is a condition that checks if the current character char is alphabetic. The .isalpha() method is a string method that returns True if the character is an alphabet letter and False if it's not.
    • [char for char in string if char.isalpha()]: This is the list comprehension itself. It iterates through each character in the string and, for each character that is alphabetic, includes it in the new list.
  • print(chars): This line of code prints the chars list to the console.

Source Code

string = "Hello, world!"
chars = [char for char in string if char.isalpha()]
print(chars)

Output

['H', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']

Example Programs