惠。如何将字符串更改为我之前定义的变量。
这是我的代码:
A = 'A.mpeg'
B = 'B.mpeg'
C = 'C.mpeg'
D = 'D.mpeg'
E = 'E.mpeg'
F = 'F.mpeg'
G = 'G.mpeg'
k = 'AAABBCCDD'
k = list(k)
print(k)
for i in range(len(k)):
print(i, k[i])
pygame.mixer.music.load(k[i])
pygame.mixer.music.play()
time.sleep(0.7)
我得到的错误是pygame.error: Couldn't open 'A'
。我假设我需要转换k [0] =' A'只是A作为之前定义的变量A i。
谢谢。
答案 0 :(得分:4)
或者,可以使用dict
,例如:
files = {
'A': 'A.mpeg',
'B': 'B.mpeg',
...
}
k = 'AAABBCCDD'
for i, f in enumerate(k):
print(i, files[f])
pygame.mixer.music.load(files[f])
pygame.mixer.music.play()
time.sleep(0.7)
答案 1 :(得分:1)
尝试
A = 'A.mpeg'
B = 'B.mpeg'
C = 'C.mpeg'
D = 'D.mpeg'
E = 'E.mpeg'
F = 'F.mpeg'
G = 'G.mpeg'
k = [A,B,C,D,E,F,G]
for i in range(len(k)):
print(i, k[i])
pygame.mixer.music.load(k[i])
pygame.mixer.music.play()
time.sleep(0.7)
以前,您尝试加载一个名为' A'的文件,我认为该文件不存在。
答案 2 :(得分:0)
您可以使用eval功能:
A = 'A.mpeg'
B = 'B.mpeg'
C = 'C.mpeg'
D = 'D.mpeg'
E = 'E.mpeg'
F = 'F.mpeg'
G = 'G.mpeg'
k = [A,B,C,D,E,F,G]
for i in range(len(k)):
print(i, k[i])
pygame.mixer.music.load(eval(k[i]))
pygame.mixer.music.play()
time.sleep(0.7)