Python 如何生成随机字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37675280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:47:02  来源:igfitidea点击:

How to generate a random string

pythonpython-3.x

提问by Izzy

I'm trying to do a code where is generates a random string, but I have only just started coding so I don't want anything to the code to be too complicated.

我正在尝试编写一个生成随机字符串的代码,但我才刚刚开始编码,所以我不希望代码太复杂。

import random, string
randomthing = random.choice(string)
print(randomthing(10))

But it keeps saying the length (len) is not defined. What should I do?

但它一直说长度(len)没有定义。我该怎么办?

回答by Aravindh

In case, you want to generate unique strings:

如果您想生成唯一的字符串:

import uuid
print uuid.uuid4() # e3c8a1c3-9965-4356-9072-1002632a96e1
print uuid.uuid4().hex # e3c8a1c39965435690721002632a96e1

回答by Abdul Fatir

stringmodule does not have lenyou might want to try this:

string模块没有len你可能想试试这个:

Python2:

蟒蛇2:

rand_str = lambda n: ''.join([random.choice(string.lowercase) for i in xrange(n)])

# Now to generate a random string of length 10
s = rand_str(10)  

Python3:

蟒蛇3:

rand_str = lambda n: ''.join([random.choice(string.ascii_lowercase) for i in xrange(n)])

# Now to generate a random string of length 10
s = rand_str(10)  

random.choicereturns a single character and 10 such characters are joined using the joinfunction.

random.choice返回单个字符,并使用该join函数连接 10 个这样的字符。

EDIT

编辑

lambda n : ...creates a lambda function which takes nas the argument.

lambda n : ...创建一个以n参数为参数的 lambda 函数。

''.join(sequence)joins a sequence into a string with empty string ('') between them i.e. it simply joins characters into words.
'.'.join(['a','b','c'])will for example, return a.b.c.

''.join(sequence)将一个序列连接成一个字符串,''它们之间有空字符串 ( ),即它只是将字符连接成单词。
'.'.join(['a','b','c'])例如,将返回a.b.c

回答by Vijayanand Premnath

This has been already answered in Random strings in PythonGenerating strings from (for example) lowercase characters:

这已经在 PythonGenerating strings from (for example) smallcase characters中的随机字符串中得到了回答:

import random, string

def randomword(length):
   return ''.join(random.choice(string.lowercase) for i in range(length))

Results:

结果:

>>> randomword(10)
'vxnxikmhdc'
>>> randomword(10)
'ytqhdohksy'

回答by David Guyon

Whenever I think about random strings it reminds me about Lorem Ipsum. It exists the loremipsum python packagewhich you can use like this:

每当我想到随机字符串时,它就会让我想起Lorem Ipsum。它存在loremipsum python 包,您可以像这样使用它:

from loremipsum import get_sentences
sentences_list = get_sentences(5)

If you don't mind about the exact number of char in the string, it may be a nice solution to generate random strings that look like sentences.

如果您不介意字符串中字符的确切数量,生成看起来像句子的随机字符串可能是一个不错的解决方案。

回答by Dark Force 8

STEP 1:

第1步:

Generate a random number between 97 and 122 (including both) using random.randint(97,122)

使用以下方法生成 97 到 122(包括两者)之间的随机数 random.randint(97,122)

STEP 2:

第2步:

Convert the random number to a letter using str(unichr(<random number>))

使用将随机数转换为字母 str(unichr(<random number>))

STEP 3:

第 3 步:

Append the string to the final string

将字符串附加到最终字符串

something like:

就像是:

randomString=""
for i in range(10):
    randomString += (str(unichr(random.randint(97,122)))) #intended to put tab space.
print randomString                                        #I'm new to Stackoverflow