Put a variable inside a spin?

Asked

Viewed 128 times

-1

import spintax

nome1 = input("Nome: ")
nome2 = input("Nome: ")
nome3 = input("Nome: ")
for z in range(0,10):
    c = (spintax.spin("{noite|dia|tarde}")
    print("Boa {}".format(c))

I wanted to put the variables nome within a new variable similar to the variable c. How could I do that?

2 answers

1

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}
    
  • The method str.format

    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.

1

I believe that answers your question

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"Olá {n}, bom(a) {c}")

Brief comments

  1. In the code of your post was c = (spintax... and this parenthesis was not being closed, but as it is not necessary, I withdrew.

  2. To include the data I concateni strings and used f-string (available from version 3.6 of Python

I hope it helps.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.