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

1

I want the keyword "2 orange juice" in the variable N to store the number and :

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

food="food juice"

The code is below and went as far as I could 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)
    
asked by anonymous 31.05.2017 / 18:47

3 answers

1

You can use the partition to separate the string by the first occurrence of the character it you pass as a 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)

Result:

  

2
  orange juice

See working at Ideone .

So you can have a number longer than 1 digit so your code will still work correctly.

    
31.05.2017 / 19:02
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:])
    
31.05.2017 / 18:53
0

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

Separating the quantity and product from the comma.

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

print(numero)
print(alimento)

Output:

>>> > 1, suco
>>> 1
>>> suco
    
31.05.2017 / 18:57