Python:在随机位置插入字符

3 投票
3 回答
4427 浏览
提问于 2025-04-17 03:20

比如说:

str = 'Hello world. Hello world.'

就变成了:

list = ['!','-','=','~','|']
str = 'He!l-lo wor~ld|.- H~el=lo -w!or~ld.'

3 个回答

0

Python 3 解决方案

受到 DrTyrsa 的启发

import random

lst = ['!','-','=','~','|']
string = 'Hello world. Hello world.'

使用 f-字符串:

print(''.join(f"{x}{random.choice(lst) if random.randint(0,1) else ''}" for x in string))

使用 str.format() 方法

print(''.join("{}{}".format(x, random.choice(lst) if random.randint(0,1) else '') for x in string)) 

我把 random() > 0.5 替换成 randint(0,1),因为我觉得后者虽然有点啰嗦,但同时又更简洁。

1

这里有一种方法,虽然在清晰度上比较好,但在性能方面可能不是最优的。

from random import randint
string = 'Hello world. Hello world.'

for char in ['!','-','=','~','|']:
    pos = randint(0, len(string) - 1)  # pick random position to insert char
    string = "".join((string[:pos], char, string[pos:]))  # insert char at pos

print string

更新

这段内容取自于我对一个相关问题的回答,基本上是源自于DrTysra的回答:

from random import choice
S = 'Hello world. Hello world.'
L = ['!','-','=','~','|']
print ''.join('%s%s' % (x, choice((choice(L), ""))) for x in S)
8

在编程中,有时候我们需要让程序在特定的条件下执行某些操作。比如说,当用户点击一个按钮时,程序就会做出反应。这种反应可以是显示一条消息,或者是改变页面上的内容。

为了实现这些功能,我们通常会使用“事件”。事件就像是程序中的信号,告诉程序发生了什么事情。比如,用户点击了按钮,这个点击动作就是一个事件。

在代码中,我们可以设置一些“监听器”,它们就像是守卫,时刻关注着这些事件。一旦事件发生,监听器就会立刻执行我们预先设定好的操作。

这样一来,程序就能根据用户的操作做出相应的反应,让整个应用变得更加互动和友好。

import random

lst = ['!','-','=','~','|']
string = 'Hello world. Hello world.'


print ''.join('%s%s' % (x, random.choice(lst) if random.random() > 0.5 else '') for x in string)

撰写回答