jeudi 12 mai 2016

How to assign variable to string of elements in a list rather than those elements separately? (Python 3)

I'm having some trouble in regards to assigning a variable to a specific string of elements. So basically, here's a simplified version of my code:

import random
import string

def printsl(string):
    import sys
    sys.stdout.write(string)
    sys.stdout.flush()



l = random.sample(string.ascii_lowercase, 26)
w = random.sample(l, random.randint(4, 10))

for elem in w:
    x = elem     #<------- 
    printsl(x)

print('')
printsl(x)

And when I run this code the output is something along the lines of

npabjcevz
z

or

znoyhe
e

etc. the first line of output is what I wanted it to be, however for some reason the second line only prints the last letter of the string. Correct me if I'm wrong but I'm guessing it's because instead of elem equaling the whole string of random elements it gets reassigned to 4-10 different elements and prints all of them for printsl(x) under "for elem in w" but the second time it just uses the most recent letter.
I guess my question is, how do I get it to print the full string both times? or more specifically how to I get x to equal the entire string of output?

the only thing I could think of to try was changing x = elem to x = str(elem) but it gave the same result




Aucun commentaire:

Enregistrer un commentaire