Skip to main content
 首页 » 编程设计

python之如何在 python 中生成具有特定长度的任意字符串

2025年05月04日22jyk

我需要一个 100000 个字符长的字符串。在 python 中生成这样一个字符串的最有效和最短的方法是什么?
字符串的内容并不重要。

请您参考如下方法:

类似于:

'x' * 100000 # or, 
 
''.join('x' for x in xrange(100000)) # or, 
 
from itertools import repeat 
''.join(repeat('x', times=100000)) 

或者对于一些字母的混合:

from string import ascii_letters 
from random import choice 
''.join(choice(ascii_letters) for _ in xrange(100000)) 

或者,对于一些随机数据:

import os 
s = os.urandom(100000)