How to store an int and a complete string from within an input?

Asked

Viewed 966 times

1

I wish that at the time of typing in the variable N the word "2 orange juice" the file stores in the variables number and food:

number = 2 (preferably integer, but anything I convert it after)

food = "juice of food"

The code is down and that’s as far as I can get:

suco_laranja = "suco de laranja"
morango = "morango fresco"
mamao = "mamao"
goiaba = "goiaba vermelha"
manga = "manga"
laranja = "laranja"
brocolis = "brocolis"


T = int(input(""))
for i in range(T):
    N = input()
    numero, alimento = N.split()

print(numero)
print(alimento)

3 answers

1

If the number is always the first input element entered, a simple way to solve this would be to use slicing.

N = N.split()
numero = int(N[0])
alimento = ' '.join(N[1:])

1


You can use the Partition to separate the string by the first occurrence of the character you pass as parameter, in case you want to separate by the space character of the string. Example:

entrada = '2 sucos de laranja'
numero, _, alimento = entrada.partition(' ')
print(numero)
print(alimento)

Upshot:

2
orange juices

See working on Ideone.

So you can have number with more than 1 digit that your code will still work properly.

0

It can also be made that way, similar to the one you tried.

Separating quantity and product from comma.

numero,alimento = input("> ").split(', ')

print(numero)
print(alimento)

exit:

>>> > 1, suco
>>> 1
>>> suco

Browser other questions tagged

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