简体   繁体   中英

How can I change this code generator from a list to a string (python)

import random
import string
import random
    
letter = random.choice(string.ascii_letters)
print("String as asscii letters:\n", string.ascii_letters)
print("Letter:", letter)    

number = random.randint(1111,9999)
print("Number:" , number)

verification = []
verification.append(number)
verification.append(letter)
print("Verification:", verification)

This is just a random code I was making for learning purposes but I want to learn how I can change the list to strings.

There are two main ways to do this. If you want to preserve the brackets, you can use the str method:

my_string = str(verrification)

or, using the join method:

my_string = "[" + ", ".join(str(i) for i in verrification) + "]"

If you don't want to keep the brackets:

my_string = ", ".join(str(i) for i in verrification)

Please note you have to make all items a string in order to use the join method. Here, I am using a generator expression to convert all items into a string. This is a very basic problem, so I would suggest searching up a tutorial or looking at a beginner's course to python.

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