【问题标题】:Replace each occurrence of sub-strings in the string with randomly generated values用随机生成的值替换字符串中每次出现的子字符串
【发布时间】:2017-01-30 16:44:58
【问题描述】:

我有这样的字符串:

"What is var + var?"
"Find the midpoint between (var,var) and (var,var)"

我想将上述句子中每次出现的vars 更改为随机不同的整数。我当前的代码是:

question = question.replace("var",str(random.randint(-10,10)))

这只是把所有的整数变成同一个随机生成的数,例如;

"Find the midpoint between (5,5) and (5,5)"

我知道for 循环不能用于字符串,如何将子字符串“var”更改为不同的值而不是生成的单个数字?

【问题讨论】:

  • (1) Python 中的字符串是不可变的,您无法更改它们。 (2) Read about string formatting,这可能会帮助您提出正确的问题。

标签: python string substring


【解决方案1】:

您可以使用str.format 来实现:

import random

my_str = "Find the midpoint between (var,var) and (var,var)"

var_count = my_str.count("var") # count of `var` sub-string
format_str = my_str.replace('var', '{}') # create valid formatted string

# replace each `{}` in formatted string with random `int`
new_str = format_str.format(*(random.randint(-10, 10) for _ in range(var_count)))

new_str 的位置如下:

'Find the midpoint between (6,-10) and (-5,2)'

建议:最好在原字符串中使用'{}'而不是'var'(因为python是根据{}进行格式化的)。因此,在上述解决方案中,您可以跳过 .replace() 部分。


字符串格式相关的参考

【讨论】:

  • 除了您必须存储随机值并对其进行排序,否则没有人可以检查您的答案是否正确:)
【解决方案2】:

您可以使用以下代码使其更容易:

pattern  = "Find the midpoint between (%s, %s) and (%s, %s)"
question = pattern % (str(1), str(2), str(3.0), str(4))
print(question)
>>> Find the midpoint between (1, 2) and (3.0, 4)

【讨论】:

    【解决方案3】:

    您可以使用字符串格式,如下所示:

    "What is {} + {}?".format(random.randint(-10,10), random.randint(-10,10))
    

    和:

    four_random_numbers = [random.randint(-10, 10) for _ in range(4)]
    "Find the midpoint between ({}, {}) and ({}, {})".format(*four_random_numbers)
    

    您可以轻松地将其重写为一个返回 n 个随机数的函数,以便在您的问题中使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-07
      • 2018-05-21
      • 1970-01-01
      • 2017-08-06
      • 1970-01-01
      • 2016-12-19
      • 2017-05-20
      • 2021-11-09
      相关资源
      最近更新 更多