Python: How can I make more variables from a string

时间:2017-03-02 23:35:35

标签: python string algorithm variables char

I have str="TextHere" I want to split that variable into letters and then make a different variable for each letter. How can I do this if I don´t know how many letters are in my string?

2 个答案:

答案 0 :(得分:1)

As a general rule creating an unknown number of variables is a bad idea, because it makes the scope opaque. As an alternative, create a dictionary, and store the values in the dictionary:

char_dict = {}
for char in string:
    var_name = create_var_name(char)
    char_dict[var_name] = get_value(char)

create_var_name is whatever code you have to name the variable based on the character. get_value is whatever code you have to determine the value of the variable.

答案 1 :(得分:0)

use the built_in list Function

str = "Hello"
>>> list(str)
['h', 'e', 'l', 'l', 'o']

iterating over characters of the string:

charlist = []
for character in string:
    charlist.append(character)

pythonic way:

charlist = [character for character in string]