给定字符串:
s = 'The quick brown fox jumps over the lazy dog'
如何随机选择一个令牌,交换该令牌中的两个字母,并返回带有修改后的令牌的字符串?例如:
The quick brown fxo jumps over the lazy dog
在上面的示例中,随机选择令牌
(*)
,并交换两个字符。到目前为止,我试图:
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个以上的字母转置,我不知道如何保持顺序内的标记字符串。你知道怎样用一种更像蟒蛇的方式得到
fox
吗? 最佳答案
你可以这样做:
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)