从给定字符生成固定长度随机字符串的内置方法

时间:2012-01-18 23:30:02

标签: string random python

这就是我的问题所在:我需要制作一个长度为50个字符的随机字符串,由10组成。

我知道如何解决这个问题,甚至还有一个单行。我也在SO上寻找了解决这个问题的各种解决方案,只是为了找回我已经知道的内容(12等)。但我真正想要的是最好的 Pythonic方式。

目前,我倾向于''.join(( random.choice([0,1]) for i in xrange(50) ))

有更多的pythonic方式吗?是否有内置功能,可能在itertools

4 个答案:

答案 0 :(得分:6)

对于Python2.7或更高版本:

In [83]: import random

In [84]: '{:050b}'.format(random.randrange(1<<50))
Out[84]: '10011110110110000011111000011100101111101001001011'

(在Python2.6中,使用'{0:050b}'代替'{:050b}'。)


<强>解释

string.format方法可以将整数转换为二进制字符串表示形式。执行此操作的基本格式代码为'{:b}'

In [91]: '{:b}'.format(10)
Out[91]: '1010'

要制作宽度为50的字符串,请使用格式代码'{:50b}'

In [92]: '{:50b}'.format(10)
Out[92]: '                                              1010'

并用零填充空格,使用{:050b}

In [93]: '{:050b}'.format(10)
Out[93]: '00000000000000000000000000000000000000000000001010'

syntax for str.format起初有点令人生畏。 这是我的备忘单:

http://docs.python.org/library/string.html#format-string-syntax
replacement_field ::= "{" field_name ["!" conversion] [":" format_spec] "}"
field_name        ::= (identifier|integer)("."attribute_name|"["element_index"]")* 
attribute_name    ::= identifier
element_index     ::= integer
conversion        ::= "r" | "s"
format_spec       ::= [[fill]align][sign][#][0][width][,][.precision][type]
fill              ::= <a character other than '}'>
align             ::= "<" | ">" | "=" | "^"
                      "=" forces the padding to be placed after the sign (if any)
                          but before the digits. (for numeric types)
                      "<" left justification
                      ">" right justification 
                      "^" center justification
sign              ::= "+" | "-" | " "
                      "+" places a plus/minus sign for all numbers    
                      "-" places a sign only for negative numbers
                      " " places a leading space for positive numbers
#                     for integers with type b,o,x, tells format to prefix
                      output with 0b, 0o, or 0x.
0                     enables zero-padding. equivalent to 0= fill align.
width             ::= integer
,                     tells format to use a comma for a thousands separator
precision         ::= integer
type              ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" |
                      "o" | "x" | "X" | "%"
    c convert integer to corresponding unicode character
    n uses a locale-aware separator
    % multiplies number by 100, display in 'f' format, with percent sign

答案 1 :(得分:2)

# Choose a number in [0, 1L << 50), and format it as binary.
# The [2:] lops off the prefix "0b"
bit_str = bin(random.randint(0, (1L << 50) - 1))[2:]
# We then need to pad to 50 bits.
fifty_random_bits = '%s%s' % ('0' * (50 - len(bit_str)), bit_str)

答案 2 :(得分:2)

对我来说这看起来很诡异。 如果您希望保存字符,则可能会丢失括号:

''.join( random.choice(['0','1']) for i in xrange(50) )

答案 3 :(得分:0)

from random import choice
from itertools import repeat
# map or generator expression, take your pick
"".join( map( choice, repeat( "01", 50)))
"".join( choice(x) for x in repeat("01", 50))

将输入更改为repeat以进行概括。