Tuple of characters in a string in Python


This Python code converts a string into a tuple called char_tuple, where each element of the tuple corresponds to a character in the original string. Here's how the code works:

  • string = "hello": This line initializes a variable named string and assigns it the string "hello."
  • char_tuple = tuple(char for char in string): This line of code initializes a variable named char_tuple and assigns it a tuple created using a generator expression.
    • char for char in string: This part of the code uses a generator expression to iterate through each character char in the string.
    • tuple(...): This surrounds the generator expression and converts the generated characters into a tuple.
  • print(string): This line of code prints the original string to the console.
  • print(char_tuple): This line of code prints the char_tuple tuple (which contains the individual characters from the string) to the console.

Source Code

string = "hello"
char_tuple = tuple(char for char in string)
print(string)
print(char_tuple)

Output

hello
('h', 'e', 'l', 'l', 'o')

Example Programs