我从文件中读取了一行:
a b c d e f
有了这个字符串,我想把每个字母变成一个新的"用户"在我的用户类中。所以我想要的是:
for character in **the first line of the file**:
if character != ' '
user = user(character)
换句话说,我想要像" userA = user(" a")&#34 ;,其中user是我定义为接受字符串作为参数的类。
我很难找到在Python中迭代字符串的方法,然后使用结果创建一个对象。
答案 0 :(得分:6)
您不能在作业的左侧添加附加内容(您不能以这种方式构造变体名称)。您应该使用字典和str.split
方法:
users = {} # note the plural, this is not 'user', but 'users'
for name in myString.split():
users[name] = user(name)
您还可以使用词典理解来实现相同目的:
users = { name : user(name) for name in myString.split() }