问题:Python中的随机字符串

如何在Python中创建随机字符串?

我需要先编号然后重复字符,直到完成为止

def random_id(length):
    number = '0123456789'
    alpha = 'abcdefghijklmnopqrstuvwxyz'
    id = ''
    for i in range(0,length,2):
        id += random.choice(number)
        id += random.choice(alpha)
    return id

How do you create a random string in Python?

I needed it to be number then character repeat till you’re done this is what I created

def random_id(length):
    number = '0123456789'
    alpha = 'abcdefghijklmnopqrstuvwxyz'
    id = ''
    for i in range(0,length,2):
        id += random.choice(number)
        id += random.choice(alpha)
    return id

回答 0

从(例如)小写字符生成字符串:

import random, string

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

结果:

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

Generating strings from (for example) lowercase characters:

import random, string

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

Results:

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

回答 1

由于这个问题是相当随机的,所以这可能对您有用:

>>> import uuid
>>> print uuid.uuid4()
58fe9784-f60a-42bc-aa94-eb8f1a7e5c17

Since this question is fairly, uh, random, this may work for you:

>>> import uuid
>>> print uuid.uuid4()
58fe9784-f60a-42bc-aa94-eb8f1a7e5c17

回答 2

>>> import random
>>> import string
>>> s=string.lowercase+string.digits
>>> ''.join(random.sample(s,10))
'jw72qidagk
>>> import random
>>> import string
>>> s=string.lowercase+string.digits
>>> ''.join(random.sample(s,10))
'jw72qidagk

回答 3

回答原始问题:

os.urandom(n)

引用自:http : //docs.python.org/2/library/os.html

返回适合加密用途的n个随机字节的字符串。

该函数从特定于操作系统的随机性源返回随机字节。尽管返回的数据的确切质量取决于操作系统的实现,但是对于加密应用程序而言,返回的数据应该足够不可预测。在类似UNIX的系统上,它将查询/ dev / urandom,在Windows上,它将使用CryptGenRandom。如果找不到随机源,则将引发NotImplementedError。

有关平台所提供的随机数生成器的易于使用的界面,请参阅random.SystemRandom。

Answer to the original question:

os.urandom(n)

Quote from: http://docs.python.org/2/library/os.html

Return a string of n random bytes suitable for cryptographic use.

This function returns random bytes from an OS-specific randomness source. The returned data should be unpredictable enough for cryptographic applications, though its exact quality depends on the OS implementation. On a UNIX-like system this will query /dev/urandom, and on Windows it will use CryptGenRandom. If a randomness source is not found, NotImplementedError will be raised.

For an easy-to-use interface to the random number generator provided by your platform, please see random.SystemRandom.


回答 4

您可以构建随机的ascii字符,例如:

import random
print chr(random.randint(0,255))

然后构建一个更长的字符串,例如:

len = 50
print ''.join( [chr(random.randint(0,255)) for i in xrange(0,len)] )

You can build random ascii characters like:

import random
print chr(random.randint(0,255))

And then build up a longer string like:

len = 50
print ''.join( [chr(random.randint(0,255)) for i in xrange(0,len)] )

回答 5

关于所需的随机字符串类型,您实际上并没有说太多。但是无论如何,您都应该研究该random模块。

下面粘贴了一个非常简单的解决方案。

import random

def randstring(length=10):
    valid_letters='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    return ''.join((random.choice(valid_letters) for i in xrange(length)))

print randstring()
print randstring(20)

You haven’t really said much about what sort of random string you need. But in any case, you should look into the random module.

A very simple solution is pasted below.

import random

def randstring(length=10):
    valid_letters='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    return ''.join((random.choice(valid_letters) for i in xrange(length)))

print randstring()
print randstring(20)

回答 6

有时,我想要的是半发音,半记忆的随机字符串。

import random

def randomWord(length=5):
    consonants="bcdfghjklmnpqrstvwxyz"
    vowels="aeiou"

    return "".join(random.choice((consonants,vowels)[i%2]) for i in range(length))

然后,

>>> randomWord()
nibit
>>> randomWord()
piber
>>> randomWord(10)
rubirikiro

为避免使用4个字母的单词,请不要设置length为4。

吉姆

Sometimes, I’ve wanted random strings that are semi-pronounceable, semi-memorable.

import random

def randomWord(length=5):
    consonants = "bcdfghjklmnpqrstvwxyz"
    vowels = "aeiou"

    return "".join(random.choice((consonants, vowels)[i%2]) for i in range(length))

Then,

>>> randomWord()
nibit
>>> randomWord()
piber
>>> randomWord(10)
rubirikiro

To avoid 4-letter words, don’t set length to 4.

Jim


回答 7

random_name = lambda length: ''.join(random.sample(string.letters, length))

长度必须为<= len(string.letters)=53。结果示例

   >>> [random_name(x) for x in range(1,20)]
['V', 'Rq', 'YtL', 'AmUF', 'loFdS', 'eNpRFy', 'iWFGtDz', 'ZTNgCvLA', 'fjUDXJvMP', 'EBrPcYKUvZ', 'GmxPKCnbfih', 'nSiNmCRktdWZ', 'VWKSsGwlBeXUr', 'i
stIFGTUlZqnav', 'bqfwgBhyTJMUEzF', 'VLXlPiQnhptZyoHq', 'BXWATvwLCUcVesFfk', 'jLngHmTBtoOSsQlezV', 'JOUhklIwDBMFzrTCPub']
>>> 

请享用。;)

random_name = lambda length: ''.join(random.sample(string.letters, length))

length must be <= len(string.letters) = 53. result example

   >>> [random_name(x) for x in range(1,20)]
['V', 'Rq', 'YtL', 'AmUF', 'loFdS', 'eNpRFy', 'iWFGtDz', 'ZTNgCvLA', 'fjUDXJvMP', 'EBrPcYKUvZ', 'GmxPKCnbfih', 'nSiNmCRktdWZ', 'VWKSsGwlBeXUr', 'i
stIFGTUlZqnav', 'bqfwgBhyTJMUEzF', 'VLXlPiQnhptZyoHq', 'BXWATvwLCUcVesFfk', 'jLngHmTBtoOSsQlezV', 'JOUhklIwDBMFzrTCPub']
>>> 

Enjoy. ;)


回答 8

安装此软件包:

pip3 install py_essentials

并使用以下代码:

from py_essentials import simpleRandom as sr
print(sr.randomString(4))

有关方法其他参数的更多信息,请参见此处。

Install this package:

pip3 install py_essentials

And use this code:

from py_essentials import simpleRandom as sr
print(sr.randomString(4))

More informations about the method other parameters are available here.


回答 9

此函数生成由大写,小写字母,数字组成的随机字符串,传递长度分隔符,no_of_blocks以指定您的字符串格式

例如:len_sep = 4,no_of_blocks = 4将生成以下模式,

F4nQ-Vh5z-JKEC-WhuS

长度分隔符将在4个字符后添加“-”

XXXX-

没有块将生成以下字符组成的字符串

XXXX-XXXX-XXXX-XXXX

如果需要单个随机字符串,则只需使no_of_blocks变量等于1,并保持len_sep来指定随机字符串的长度。

例如:len_sep = 10,no_of_blocks = 1,将生成以下模式,即。长度为10的随机字符串,

F01xgCdoDU

import random as r

def generate_random_string(len_sep, no_of_blocks):
    random_string = ''
    random_str_seq = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    for i in range(0,len_sep*no_of_blocks):
        if i % len_sep == 0 and i != 0:
            random_string += '-'
        random_string += str(random_str_seq[r.randint(0, len(random_str_seq) - 1)])
    return random_string

This function generates random string consisting of upper,lowercase letters, digits, pass the length seperator, no_of_blocks to specify your string format

eg: len_sep = 4, no_of_blocks = 4 will generate the following pattern,

F4nQ-Vh5z-JKEC-WhuS

Where, length seperator will add “-” after 4 characters

XXXX-

no of blocks will generate the following patten of characters as string

XXXX – XXXX – XXXX – XXXX

if a single random string is needed, just keep the no_of_blocks variable to be equal to 1 and len_sep to specify the length of the random string.

eg: len_sep = 10, no_of_blocks = 1, will generate the following pattern ie. random string of length 10,

F01xgCdoDU

import random as r

def generate_random_string(len_sep, no_of_blocks):
    random_string = ''
    random_str_seq = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    for i in range(0,len_sep*no_of_blocks):
        if i % len_sep == 0 and i != 0:
            random_string += '-'
        random_string += str(random_str_seq[r.randint(0, len(random_str_seq) - 1)])
    return random_string

回答 10

import random 
import string

def get_random_string(size):
    chars = string.ascii_lowercase+string.ascii_uppercase+string.digits
    ''.join(random.choice(chars) for _ in range(size))

print(get_random_string(20)

输出:FfxjmkyyLG5HvLeRudDS

import random 
import string

def get_random_string(size):
    chars = string.ascii_lowercase+string.ascii_uppercase+string.digits
    ''.join(random.choice(chars) for _ in range(size))

print(get_random_string(20)

output : FfxjmkyyLG5HvLeRudDS


回答 11

python3.6+你可以使用secrets模块

机密模块用于生成适合于管理数据(例如密码,帐户身份验证,安全令牌和相关机密)的密码学强随机数。

特别是,应优先使用随机模块中默认的伪随机数生成器(它是为建模和仿真而不是安全性或密码术设计的)中的默认伪随机数生成器。

在测试768bit安全令牌的生成时,我发现:

  • random.choices()0.000246
  • secrets.choice()0.003529

这些secrets模块速度较慢,但​​是在测试之外,您应该将其用于加密目的:

import string, secrets

def random_string(size):        
        letters = string.ascii_lowercase+string.ascii_uppercase+string.digits            
        return ''.join(secrets.choice(letters) for i in range(size))

print(random_string(768))

In python3.6+ you can use the secrets module:

The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.

In particularly, secrets should be used in preference to the default pseudo-random number generator in the random module, which is designed for modelling and simulation, not security or cryptography.

In testing generation of 768bit security tokens I found:

  • random.choices()0.000246 secs
  • secrets.choice()0.003529 secs

The secrets modules is slower but outside of testing it is what you should be using for cryptographic purposes:

import string, secrets

def random_string(size):        
        letters = string.ascii_lowercase+string.ascii_uppercase+string.digits            
        return ''.join(secrets.choice(letters) for i in range(size))

print(random_string(768))

回答 12

尝试从随机导入中导入以下软件包*

try importing the below package from random import*


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。