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

4 投票
4 回答
894 浏览
提问于 2025-04-17 10:34

我遇到的问题是:我需要生成一个长度为50的随机字符串,里面只包含10

我知道怎么解决这个问题,甚至有一个一行代码就能搞定。我也在StackOverflow上找过各种解决方案,但得到的都是我已经知道的内容(比如12等)。但我真正想要的是最符合Python风格的方法。

目前,我倾向于使用''.join(( random.choice([0,1]) for i in xrange(50) ))这个方法。

有没有更符合Python风格的方法?有没有什么内置的功能可以做到这一点,可能在itertools里?

4 个回答

3

在我看来,这看起来很像Python的风格。
如果你想节省字符,可以去掉括号:

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

在编程中,有时候我们会遇到一些问题,比如代码运行不正常或者出现错误。这些问题可能是因为我们写的代码不够清晰,或者没有考虑到某些情况。为了帮助大家更好地理解这些问题,我们可以通过一些简单的例子来说明。

比如说,当你在写一个程序时,如果你没有正确地设置变量,或者没有按照正确的顺序执行代码,就可能导致程序出错。就像做菜一样,如果你把材料放错了位置,或者步骤搞混了,最后做出来的菜可能就不好吃。

所以,编程的时候要特别注意代码的逻辑和顺序,确保每一步都是正确的。这样才能让程序顺利运行,达到我们想要的效果。

# 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)
7

对于 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'

对于 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

撰写回答