简体   繁体   English

如何将此代码生成器从列表更改为字符串(python)

[英]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.

相关问题 如何将列表中的 dataframe 名称更改为带有 python 的字符串? - How can I change dataframe names in a list to string with python? 如何更改一个文件中的所有代码,其中字符串等于 python 中另一个文件中的字符串。 我会在例子中解释 - How can i change all code from one file where string equals to string in another file in python. I will explain in example 我如何从python生成器获取数据 - How can I get data from python generator 如何在 Python 中将变量从一个生成器传递到另一个生成器? - How can I pass a variable from one generator to another in Python? 在python中没有重复代码的情况下,简单的方法将生成器更改为列表理解? - Easy way to change generator into list comprehension without duplicating code in python? 如何从 Python 中的字符串中提取数字并返回一个列表? - How can I extract numbers from a string in Python, and return a list? Python从生成器到列表 - Python from generator to list 如何在此代码中连接列表和字符串? - How can I concatenate list and string in this code? 如何比较 2 个列表并从 1 个列表中删除包含其他列表中的 substring 的字符串? Python - How can I compare 2 list and remove the a string from 1 list that contain a substring from other list? Python 如何查找/编写带有前缀字符和顺序的字符串/代码生成器(最好在 Python 或 Java 中) - How do i find/write a String/code generator with prefix char and order (preferably in Python or Java)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM