0

How do I condense a list into string that I can use in my code later?

For example:

result = []
bin = []
j = 0
while j<5:
    bin.append(j)
    j=j+1

#Pseudo code:
a = ''.join(map(int, bin)
result.append(a)

Basically, I want it to do this:

bin = [0,1,2,3,4]

result = [01234]

so I can use 'result' later on in my code.

Still pretty new at this, but I appreciate your help.

Killjoy
  • 3
  • 3
  • Not sure why you would need this but: `repr(bin)[1:-1].replace(', ','')` will create a string representation of `bin`, strip off the `[` and `]` and then replace `, ` with `''` which gives you a string that looks like: `'01234'` – Farhan.K Nov 14 '16 at 11:44
  • Possible duplicate of [Converting a list to a string](http://stackoverflow.com/questions/2906092/converting-a-list-to-a-string) – airudah Nov 14 '16 at 11:45
  • @RobertUdah ''.join wouldn't work with `int` – Farhan.K Nov 14 '16 at 11:46
  • True. In which case, `str (j)` should convert the numbers to string in the loop – airudah Nov 14 '16 at 11:48
  • @RobertUdah Yep, that's another way to do this – Farhan.K Nov 14 '16 at 11:49
  • Thanks for the comments. To answer @Farhan.K 's question: I'm trying to make a scrambler of sorts that takes a combination of randomly assigned 0's & 1's, then searches for the result in a secondary table. I want to search for the index of the new number & replace it with a single character. Right now it's about 80 lines of just junk code, so I didn't want to front load with the whole mess. – Killjoy Nov 14 '16 at 12:46
  • Also, to expand on @RobertUdah 's comment; I wouldn't be surprised if it was a duplicate, but the link you sent is wwaayy over my head atm, so I couldn't tell you if it were or not. – Killjoy Nov 14 '16 at 12:50

1 Answers1

0

You could change your code like that:

result = []
bin = []
j = 0
while j<5:
    bin.append(j)
    j=j+1

#Pseudo code:
a = ''.join(str(x) for x in bin)
result.append(a)

But it look better if you use the for-loop:

l = list()
for i in range(5):
    l.append(i)

result = [ ''.join(str(x) for x in l) ]
Axel Juraske
  • 186
  • 4