简体   繁体   中英

How to assign the result of a for loop to a variable in Python

My program generates a random string with a random amount of letters from 10 to 20.

def program():
    import random
    import sys
    x=['q','w','e','r']
    y=random.randint(10,20)
    for t in range (0,y):
       w=random.randint(0,3)
       e=x[w]
       sys.stdout.write(e)

The program will print a random string like 'wwwweewwqqrrrrwwqqeeqqww'. How would I store this string as a variable?

Store it in a variable instead of writing:

e=''

for t in range (0,y):
    w=random.randint(0,3)
    e += x[w]

e is an empty variable and each time you add the value x[w] to it.

I would also recommend using print() over sys.stdout.write(e) since you do not need additional imports -such as sys , print() is inbuilt.

In this case can I suggest the use of a tuple for x=['q','w','e','r'] since they are faster. So: x=('q','w','e','r'1)

but if you are going to need to modify this later then this is not an option available to you (since they are immutable).

You could replace your loop with a list comprehension, and use join() :

e = ''.join([random.choice(x) for _ in range(0, y)])

Output:

qwewwwereeeqeqww
def program():
   import random
   x=['q','w','e','r']
   y=random.randint(10,20)
   mystr=''
   for t in range (0,y):
      w=random.randint(0,3)
      e=x[w]
      mystr=mystr+e

If you'd like you can have program() returns the output variable like so:

def program():
    import random
    import sys
    x=['q','w','e','r']
    y=random.randint(10,20)
    output = ''
    for t in range (0,y):
        w=random.randint(0,3)
        e=x[w]
        output+=e
    # The print is stored in 'output'

    # Return the output
    return output
result = program()

An easy way to do this would be to create a new string variable and just use the += operator to concatenate each character onto a new string. Your code could be

 def program():
   import random
   import sys
   x=['q','w','e','r']
   y=random.randint(10,20)
   z = '';
   for t in range (0,y):
      w=random.randint(0,3)
      e=x[w]
      z += e;

This code just adds each character to a string variable z in your for loop, and that string value should be stored in z .

something like (haven't tested the program, should work... famous last words).

# imports at start of file, not in def
import random
import sys

# I would never call a def 'program', kind of generic name, avoid
def my_program():  # camel case, PEP-8
    x=['q','w','e','r']
    z=''  # initialize result as an empty string
    for _ in range (0, random.randint(10,20)):
       z+=x[random.randint(0,3)]  # add a letter to string z
    return z  

"_" is often used for a throw away variable, see What is the purpose of the single underscore "_" variable in Python? In this case the _ is used nowhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM