在 Python 中,如何在一行代码中创建一个由 n 个字符组成的字符串? [英] In Python, how do I create a string of n characters in one line of code?

查看:28
本文介绍了在 Python 中,如何在一行代码中创建一个由 n 个字符组成的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 Python 中生成一个包含 n 个字符的字符串.是否有使用现有 Python 库实现这一目标的单行答案?例如,我需要一个由 10 个字母组成的字符串:

I need to generate a string with n characters in Python. Is there a one line answer to achieve this with the existing Python library? For instance, I need a string of 10 letters:

string_val = 'abcdefghij'

推荐答案

简单地重复同一个字母 10 次:

To simply repeat the same letter 10 times:

string_val = "x" * 10  # gives you "xxxxxxxxxx"

如果你想要更复杂的东西,比如n随机小写字母,它仍然只有一行代码(不包括导入语句和定义n):

And if you want something more complex, like n random lowercase letters, it's still only one line of code (not counting the import statements and defining n):

from random import choice
from string import ascii_lowercase
n = 10

string_val = "".join(choice(ascii_lowercase) for i in range(n))

这篇关于在 Python 中,如何在一行代码中创建一个由 n 个字符组成的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆