0

Objective

I have a string variable:

use_this_string = "If you want to <something here>, then first learn it"

and I want to insert a user input value into it like (in REPL mode):

>>> placeholder_value = input("What do you want to do: ")
What do you want to do: swim

and when the code is executed, the place_holder in use_this_string should be replaced with the value of placeholder_value variable.

Pseudo code for this would be like

use_this_string = "If you want to <something here>, then first learn it"
placeholder_value = input("What do you want to do: ")

# Not real code
print(use_this_string.insert(placeholder_value)) 
# place the inputed value into the string into placeholder position

expected output:

What do you want to do: swinm

If you want to swim, then first learn it

What I thought of

I've thought including s placeholder string in the variable like

# literally the code
use_this_string = "If you want to <placeholder>, then first learn it"

placeholder_value = input("What do you want to do: ")

print(use_this_string.replace('<placeholder>', placeholder_value)

However, I had this question for a long time, I want to use a solution often. In case the string already contained the substring <placeholder>, then it would be replaced as well. Any other solutions..? TIA

  • Use a format string, `use_this_string = "If you want to {}, then first learn it"`, and then `print(use_this_string.format(placeholder_value))` – Wiktor Stribiżew Apr 18 '21 at 11:18
  • this is called string interpolation. there are a few ways to do it python, a search engine should give good results – L.Grozinger Apr 18 '21 at 11:24

0 Answers0