Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

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:
", 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...