2

I am having strings like:

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

I want to change the each occurrence of vars in the above sentences to the random different integers. My current code code is:

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

This only made all the integers into the same randomly genererated number, For example;

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

As I'm aware that for loops cannot be used on a string, how is it possible to change the substring "var" to different values rather than that single generated number?

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
RazDoog
  • 111
  • 1
  • 7
  • 6
    (1) Strings in Python are immutable, you cannot alter them. (2) [Read about string formatting](https://pyformat.info/), this probably would help you ask the right question. – 9000 Jan 30 '17 at 16:48

3 Answers3

4

You may use str.format to achieve this as:

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)))

where new_str will hold something like:

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

Suggestion: It is better to use '{}' instead of 'var' in the original string (as python performs formatting based on {}). Hence, in the above solution you may skip the .replace() part.


References related to string formatting:

Community
  • 1
  • 1
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
0

You can use following code to make it easier:

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)
aldarel
  • 446
  • 2
  • 7
0

You can use string formatting, like so:

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

and:

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

You could easily re-write it as a function returning n-random numbers to use in your questions.

JanHak
  • 1,645
  • 1
  • 10
  • 9