【问题标题】:Is there a pythonic way to insert space characters at random positions of an existing string?有没有一种pythonic方法可以在现有字符串的随机位置插入空格字符?
【发布时间】:2010-11-28 12:15:05
【问题描述】:

有没有pythonic方法来实现这个:

插入/spaces_1/ U+0020 SPACE 字符随机进入/key_1/ 开始或结束以外的位置 字符串。

?

/spaces_1/ 是整数,/key_1/ 是任意现有字符串。

谢谢。

【问题讨论】:

  • 在给定字符串大小的情况下,插入的空格数如何分布?

标签: string python


【解决方案1】:

python 中的字符串是不可变的,因此您无法就地更改它们。然而:

import random

def insert_space(s):
    r = random.randint(1, len(s)-1)
    return s[:r] + ' ' + s[r:]

def insert_spaces(s):
    for i in xrange(random.randrange(len(s))):
        s = insert_space(s)
    return s

【讨论】:

  • 我认为先转换为列表效率更高,不是吗?
  • @eigenein,这取决于。我建议两者都试一下,看看哪个更快。
【解决方案2】:

这是一个基于列表的解决方案:

import random

def insert_spaces(s):
    s = list(s)
    for i in xrange(len(s)-1):
        while random.randrange(2):
            s[i] = s[i] + ' '
    return ''.join(s)

【讨论】:

    【解决方案3】:

    我将任意决定您永远不要相邻插入两个空格 - 每个插入点仅使用一次 - 并且“插入”不包括“追加”和“前置”。

    首先,构造一个插入点列表...

    insert_points = range (1, len (mystring))
    

    从该列表中随机选择一个,然后对其进行排序...

    import random
    selected = random.sample (insert_points, 5)
    selected.sort ()
    

    列出你的字符串切片...

    selected.append (len (mystring))  #  include the last slice
    temp = 0  #  start with first slice
    result = []
    for i in selected :
      result.append (mystring [temp:i])
      temp = i
    

    现在,构建新字符串...

    " ".join (result)
    

    【讨论】:

    • 这很有趣,但有点漫长。 =)
    • @eigenein - 至少已经有一个理智的答案,所以我瞄准了稍微疯狂的利基市场。 FWIW,可能有一种方法可以避免 for-loop 位 - 一种在指定位置拆分字符串的内置方法。我当时没想过要检查。
    • 为什么不选择 = random.sample(insert_points, random.randrange(len(mystring))) ?
    • @dan - 因为我没想到 - 好主意。
    【解决方案4】:

    仅仅因为还没有人使用map

    import random
    ''.join(map(lambda x:x+' '*random.randint(0,1), s)).strip()
    

    【讨论】:

    • 一个漂亮的解决方案。遗憾的是它没有插入精确定义的空格数。
    【解决方案5】:

    此方法在字符串中的随机位置插入给定数量的空格,并注意彼此之间没有双空格:

    import random
    
    def add_spaces(s, num_spaces):
        assert(num_spaces <= len(s) - 1)
    
        space_idx = []
        space_idx.append(random.randint(0, len(s) - 2))
        num_spaces -= 1
    
        while (num_spaces > 0):
            idx = random.randint(0, len(s) - 2)
            if (not idx in space_idx):
                space_idx.append(idx)
                num_spaces -= 1
    
        result_with_spaces = ''
        for i in range(len(s)):
            result_with_spaces += s[i]
            if i in space_idx:
                result_with_spaces += ' '
    
        return result_with_spaces
    

    【讨论】:

      【解决方案6】:

      如果你想添加多个空格,那就去

      s[:r] + ' '*n + s[r:]
      

      【讨论】:

        【解决方案7】:

        来了……

        def thePythonWay(s,n):
            n = max(0,min(n,25))
            where = random.sample(xrange(1,len(s)),n)
            return ''.join("%2s" if i in where else "%s" for i in xrange(len(s))) % tuple(s)
        

        【讨论】:

          【解决方案8】:

          我们会随机选择要加空格的位置——在字符串的char 0、1、...n-2之后(n-1是最后一个字符,之后我们不会加空格);然后通过将指定位置的字符替换为(原始字符)+''来插入空格。这与 Steve314 解决方案的思路一致(即保持您不想要连续空格的假设 - 这限制了您可以拥有的总空间),但不使用列表。

          因此:

          import random
          def insert_random_spaces(original, amount):
              assert amount > 0 and amount < len(original)
              insert_positions = sorted(random.sample(xrange(len(original) - 1), amount))
              return ''.join(
                  x + (' ' if i in insert_positions else '')
                  for (i, x) in enumerate(original)
              )
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2010-12-05
            • 2019-09-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-11-15
            • 2019-02-26
            相关资源
            最近更新 更多