开发者

Is there a pythonic way to insert space characters at random positions of an existing string?

开发者 https://www.devze.com 2023-01-27 12:03 出处:网络
is there a pythonic way to implement this: Insert /spaces_1/ U+0020 SPACE characters into /key_1/ at random

is there a pythonic way to implement this:

Insert /spaces_1/ U+0020 SPACE characters into /key_1/ at random positions other than the start or end of the string.

?

There /spaces_1/ is integer and /key_1/ is arbitrary existing strin开发者_StackOverflow社区g.

Thanks.


strings in python are immutable, so you can't change them in place. However:

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


Here's a list based solution:

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)


I'm going to arbitrarily decide you never want two spaces inserted adjacently - each insertion point used only once - and that "insert" excludes "append" and "prepend".

First, construct a list of insertion points...

insert_points = range (1, len (mystring))

Pick out a random selection from that list, and sort it...

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

Make a list of slices of your string...

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

Now, built the new string...

" ".join (result)


Just because no one used map yet:

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


This method inserts a given number of spaces to a random position in a string and takes care that there are no double spaces after each other:

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


If you want to add more than one space, then go

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


Here it comes...

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)


We will randomly choose the locations where spaces will be added - after char 0, 1, ... n-2 of the string (n-1 is the last character, and we will not place a space after that); and then insert the spaces by replacing the characters in the specified locations with (the original character) + ' '. This is along the lines of Steve314's solution (i.e. keeping the assumption that you don't want consecutive spaces - which limits the total spaces you can have), but without using lists.

Thus:

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

精彩评论

暂无评论...
验证码 换一张
取 消