给定一个字符串,如何随机转置他们的2个字母?

时间:2018-12-18 14:39:58

标签: python python-3.x string list-comprehension

给出一个字符串:

s = 'The quick brown fox jumps over the lazy dog'

我如何随机选择一个令牌,从该令牌交换两个字母,然后将字符串与修改后的令牌一起返回?例如(*)

The quick brown fxo jumps over the lazy dog

在上面的示例中,令牌fox是随机选择的,并且交换了两个字符。

到目前为止,我试图:

def swap_letters(string):
    s = list(string)
    s[0], s[len(s)-1] = s[len(s)-1].upper(), s[0].lower()
    string = ''.join(s)
    return string    


def foo(a_string):
    a_string_lis = a_string.split()
    token = random.choice(a_string_lis)
    return swap_letters(token)

但是,我换位的字母超过2个,我不知道如何在字符串中保持标记的顺序。关于如何以更Python化的方式获取(*)的想法吗?

4 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

import random
random.seed(42)

s = 'The quick brown fox jumps over the lazy dog'


def transpose(text, number=2):

    # select random token
    tokens = text.split()
    token_pos = random.choice(range(len(tokens)))

    # select random positions in token
    positions = random.sample(range(len(tokens[token_pos])), number)

    # swap the positions
    l = list(tokens[token_pos])
    for first, second in zip(positions[::2], positions[1::2]):
        l[first], l[second] = l[second], l[first]

    # replace original tokens with swapped
    tokens[token_pos] = ''.join(l)

    # return text with the swapped token
    return ' '.join(tokens)


result = transpose(s)
print(result)

输出

The iuqck brown fox jumps over the lazy dog

更新

对于长度为1的字符串,上面的代码失败了,类似这样的东西应该可以解决:

def transpose(text, number=2):

    # select random token
    tokens = text.split()
    positions = list(i for i, e in enumerate(tokens) if len(e) > 1)

    if positions:

        token_pos = random.choice(positions)

        # select random positions in token
        positions = random.sample(range(len(tokens[token_pos])), number)

        # swap the positions
        l = list(tokens[token_pos])
        for first, second in zip(positions[::2], positions[1::2]):
            l[first], l[second] = l[second], l[first]

        # replace original tokens with swapped
        tokens[token_pos] = ''.join(l)

    # return text with the swapped token
    return ' '.join(tokens)

答案 1 :(得分:2)

您可以只使用str.replace方法:

def swap_letters(string):
    s = list(string)
    s[0], s[len(s)-1] = s[len(s)-1], s[0]
    string = ''.join(s)
    return string

def foo(a_string):
    a_string_lis = a_string.split()
    token = random.choice(a_string_lis)
    return a_string.replace(token, swap_letters(token))

答案 2 :(得分:2)

    def swap_letters(string,pos,string1):
        s = list(string)
        s[len(s)-1], s[len(s)-2] = s[len(s)-2], s[len(s)-1].lower()
        string = ''.join(s)
        string1[pos[0]]=string
        s1= ' '.join(string1)
        return s1    
    def foo(a_string):
        a_string_lis = a_string.split()
        print(a_string_lis)
        token = random.choice(a_string_lis)
        pos=[i for i in range(len(a_string_lis)) if a_string_lis[i]==token]
        return swap_letters(token,pos,a_string_lis)
    s='The quick brown fox jumps over the lazy dog'
    print(foo(s))

答案 3 :(得分:1)

如何?

from random import choice, sample


s = 'The quick brown fox jumps over the lazy dog'

tokenize = s.split()
token = choice([x for x in tokenize if len(x)>2])  # choose a random word from phrase with at least 2 letters
chosen = sample(token, k=2)                        # choose two random letters word
d = dict(zip(chosen, chosen[::-1]))

new_token = ''
for letter in token:
  if letter in d:
    new_token += d[letter]
    del d[letter]
  else:
    new_token += letter

s = ' '.join([word if word != token else new_token for word in tokenize])

产生:

print(s)  # -> The quick brown fox jumps over the lyza dog
#                                                  ||