【问题标题】:Generate a random string with a random number of letters and spaces生成具有随机数量的字母和空格的随机字符串
【发布时间】:2015-02-20 00:16:22
【问题描述】:

我写了一个函数,它返回一个长度为n的随机字符串。

import string, random
def randomString(N):
    return ''.join(random.sample(string.ascii_lowercase + ' ', N))

但是,这只会返回一个字符串,其中每个字母/空格之一。我需要一个带有随机数量的小写字母和空格的字符串(字符可以重复)。

我尝试向 .join 方法添加另一个参数,但它返回语法错误。

如何更改此函数以生成随机数量的字母和空格?

【问题讨论】:

  • 那么...你的问题是什么?
  • 不,,您绝对应该在得到答案后随时更新您的问题。 SO 不是为你做功课的。
  • 我们希望您不更新您的问题。如果您有新问题,请提出新问题。此外,虽然序言很可爱,但它大多无关紧要。你的问题应该是这样的:"How can I generate a random string composed of 27 ascii lowercase letters plus the space?"这就是你真正要问的。
  • 这是你应该问的问题。其他一切要么无关紧要,要么是一个或多个未来问题的一部分。
  • @Two-BitAlchemist 我同意。有些上下文很好,但那太多了。现在清楚多了。

标签: python


【解决方案1】:

您正在寻找random.choice

import string, random
def randomString(N):
    return ''.join(random.choice(string.ascii_lowercase + ' ') for i in range(N))

【讨论】:

    【解决方案2】:
    from random import choice
    from string import ascii_lowercase
    
    # vary the number of spaces appended to adjust the probability
    chars = ascii_lowercase + " " * 10
    
    def random_string(n):
        return "".join(choice(chars) for _ in range(n))
    

    然后

    >>> print(random_string(15))
    fhr qhay nuf u 
    

    与空格数一样,您可以调整每个字符出现的次数以改变其相对概率:

    chars = (
        '                                                !,,,,,--....'
        '.....:;aaaaaaaaaaaaaaaaaaaaabbbbbcccccccccdddddddddeeeeeeeee'
        'eeeeeeeeeeeeeeeeeeeefffffggggghhhhhhhhhiiiiiiiiiiiiiiiiiiijj'
        'klllllllllmmmmmmnnnnnnnnnnnnnnnnnnooooooooooooooooppppppwrrr'
        'rrrrrrrrrrrrrssssssssssssssssttttttttttttttttttttuuuuuuuvvvw'
        'wwxyyyyz'
    )
    
    for _ in range(5):
        print(random_string(30))
    

    给予

    sxh ehredi clo-ioodmttlpoir.wo
    ijr thc -o,iepe.pcicfrn.osui.a
     et rtl teektet rrecyd.d .bate
    aji ueava hahe arv tgnrnt eecs
    a ne:tudsdu,nlnhbeirp,oioitt e
    

    【讨论】:

      【解决方案3】:

      您可以通过一个简单的循环非常轻松地做到这一点,使用 random.choice 而不是 random.sample 一次完成所有操作:

      >>> import string, random
      >>> def random_string(n):
      ...   count = 0
      ...   s = ''
      ...   while count < n:
      ...     s += random.choice(string.ascii_lowercase + ' ')
      ...     count += 1
      ...   return s
      ... 
      >>> random_string(27)
      'amwq frutj nq dbotgllrbmhnj'
      >>> random_string(27)
      'khjnmhvgzycqm vyjqcttybuqm '
      >>> random_string(27)
      'ssakcpeesfe kton gigblmgo o'
      

      【讨论】:

        猜你喜欢
        • 2014-03-07
        • 2010-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-05
        • 2011-08-18
        • 1970-01-01
        相关资源
        最近更新 更多