Python Introduction | Lists, Tuples, Ranges, Sets, and Dictionaries | Relationship Between Lists and Text
Lists are used in many places, including one that may be unexpected: text.
In Python, a text value can be handled as a list of characters. For example, the text "Hello" can be thought of as the following list of five characters.
str = ['H', 'e', 'l', 'l', 'o']
For example, str[0] retrieves the character 'H'.
This works only when retrieving characters. You cannot change characters in a string in the same way. Text and lists are not the same thing. Python simply lets you use list-like access to retrieve characters from text. This also makes it easy to search characters in a string.
The following example retrieves characters from "Hello" and creates new text.
str = "Hello"
str2 = ""
for n in str:
str2 = str2 + (n * 2) + '~'
print(str2)
When you run the code, it displays "HH~ee~ll~ll~oo~". Remember that you can use list-like operations when working with characters in text.