Вы можете сделать что-то вроде этого:
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)