Separating using + signal while reading user data

Asked

Viewed 36 times

0

Excuse me for the basic question. I just don’t understand when we have to use the + in the Input. Follow the example of a command below. Why does my code not work when I put the str(i) between commas??

i = 1
textos = []
texto = input("Digite o texto " + str(i) +" (aperte enter para sair):")

2 answers

0

You can use the formatting operator %, for example:

i = 1
textos = []
texto = input("Digite o texto %d (aperte enter para sair):" % (i) )

Or else you can use the method format(), for example:

i = 1
textos = []
texto = input("Digite o texto {} (aperte enter para sair):".format(i))
  • Interesting Lacobus - In case the (i) would be any variable? For example: text = input("Type text %d (press enter to exit):" % (5) ) would be Type ??

0

Your code does not work with commas because, by commas, you are implicitly creating a tuple (a data structure). In your case, the function input takes a string per parameter, not a tuple. Just in case, always use the sign + for concatenation, or, a function called format. Here is an example:

mensagem = 'Digite o texto {} (aperte enter para sair):'.format(i)
texto = input(mensagem)

where the {} will be replaced by the value passed by parameter in the method format (in that case the variable i).

Browser other questions tagged

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