【问题标题】:Replace substring randomly Python随机替换子字符串 Python
【发布时间】:2020-07-23 15:54:08
【问题描述】:

我正在尝试用随机的替换每次出现的 int 文字 产生的价值。但是对于每个“int”,它都会朝着相同的方向生成 每个位置的价值。如何随机更改每个位置?

if '"int"' in addstr3:              
 randint = random.randint(0, 100)                   
 addstr4 = addstr3.replace('"int"', str(randint))              
   else:                 
 addstr4 = addstr3

示例输入将是一个字符串,如“int”“int”“int”,输出将是 94 94 94

【问题讨论】:

  • 欢迎堆栈溢出!请edit您的问题提出minimal reproducible example,包括示例输入以及当前和预期输出,以便我们更好地理解您的问题
  • 您设置randint 一次,然后在replace() 中使用它,它会进行多次替换。因此,您多次获得相同的更换号码。

标签: python string random


【解决方案1】:

一种选择是利用replace() 函数的count 参数

addstr3='"int" "int" "int"'

while "int" in addstr3:
    addstr3=addstr3.replace('"int"',str(randint(0,100)),1)
    print(addstr3)

9 "int" "int"
9 29 "int"
9 29 57

【讨论】:

    猜你喜欢
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 2017-03-08
    • 2019-04-19
    相关资源
    最近更新 更多