[英]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:如果要保留括号,可以使用
str
方法:
my_string = str(verrification)
or, using the join
method:或者,使用
join
方法:
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.请注意,您必须将所有项目都设为字符串才能使用
join
方法。 Here, I am using a generator expression
to convert all items into a string.在这里,我使用
generator expression
将所有项目转换为字符串。 This is a very basic problem, so I would suggest searching up a tutorial or looking at a beginner's course to python.这是一个非常基本的问题,因此我建议您搜索教程或查看 python 的初学者课程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.