First, we must create the stirng with the pattern to be used dynamically. There are several ways to do this:
Use concatenation
You can concatenate strings in Python using the operator +
. Thus:
nome1 = "Foo"
nome2 = "Bar"
nome3 = "Baz"
print("{" + nome1 + "|" + nome2 + "|" + nome3 + "}") # {Foo|Bar|Baz}
-
You are already using it in your code to print the generated text. You can also use it to generate the pattern dynamically. So:
nome1 = "Foo"
nome2 = "Bar"
nome3 = "Baz"
print("{{{}|{}|{}}}".format(nome1, nome2, nome3)) # {Foo|Bar|Baz}
Note that, as str.format
use the keys ({
and }
) to delimit the location where the formatting will be performed, you must use {{
and }}
to insert {
or }
, respectively, in the string. Learn more in the documentation.
Use formatted literal strings (f-strings)
The functioning of f-strings is basically an interpolation of variables in a string (although it may be much more complex than that - but I won’t go into that merit). The operating pattern is also similar to the method str.format
(which we saw earlier), but occurs in a string literal. See:
nome1 = "Foo"
nome2 = "Bar"
nome3 = "Baz"
print(f"{{{nome1}|{nome2}|{nome3}}}") # {Foo|Bar|Baz}
Note that, as with the method str.format
, shall be used {{
or }}
to insert keys into the string itself.
Now you choose a way to create the pattern. Using the f-strings, we will have something like:
import spintax
nome1 = input("Nome: ")
nome2 = input("Nome: ")
nome3 = input("Nome: ")
for z in range(0, 10):
c = spintax.spin("{noite|dia|tarde}")
n = spintax.spin(f"{{{nome1}|{nome2}|{nome3}}}")
print(f"Boa {c}, {n}!")
Note that I removed an extra parenthesis that was wrong in the code (causing a syntax error). Also note that to standardize, I changed the str.format
in the print
by a f-string. See working on Repl.it.