0

Hye. How can I change a string into a variable that I have defined before.

This is my code:

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)

The error I get is pygame.error: Couldn't open 'A'. I assume I need to convert k[0] = 'A' to just A as the variable A i've defined before.

Thank you.

rmrlearn
  • 3
  • 1
  • 5

3 Answers3

4

Alternatively, a dict could be used, e.g.:

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)
AChampion
  • 29,683
  • 4
  • 59
  • 75
  • In this case it could also simply be: `file = f + '.mpeg'` .. although a dictionary (or other mapping function) is potentially more flexible. Still an up-vote for showing multiplicity/mapping via `dict`. – user2864740 Dec 31 '17 at 04:46
  • 1
    Even better, you can make the values of the dict a tuple whose first element is the name, and the second element is the number of times, so for example:`'A': ('A.mpeg', 4), 'B': ('B.mpeg', 2)` etc. – ubadub Dec 31 '17 at 04:46
  • Agreed, note sure what the OP is trying to achieve. – AChampion Dec 31 '17 at 04:46
  • Thank you. This is also works. I guess it is more appropriate to use 'dict'. Thanks again. – rmrlearn Dec 31 '17 at 05:02
  • @ubadub I intend to use k as a string of music chord. Hence it might be random. – rmrlearn Dec 31 '17 at 05:05
1

Try

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)

Previously, you were trying to load a file named 'A', which I assume did not exist.

Demetri Pananos
  • 6,770
  • 9
  • 42
  • 73
  • This doesn't accomplish what his code accomplishes. In your list, all variables appear exactly once; in his, a single letter can appear multiple times in the list, in which case the corresponding music file will be played as many times as it appears. – ubadub Dec 31 '17 at 04:45
  • Presume poster meant `k = [A, A, A, B, B, C, C, D, D]`. Note, `for i, f in enumerate(k):` would be a more canonical solution, vs. `range()` and indexing. – AChampion Dec 31 '17 at 04:45
  • 'k = [A, A, A, B, B, C, C, D, C]' works but I want the input to be as a string 'AAABBCCD' as it easier for user to type. – rmrlearn Dec 31 '17 at 04:50
0

You can use the eval function:

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)
Noa
  • 145
  • 1
  • 9