Reputation: 13
I'm using Python 3.
I need to get three values from a input (separated by a space). The values are a integer, a string and a integer again.
Consider that the string can have more than one word.
If I set two words it does not work, because each word is like a value.
My code into the momment is:
list_a = {}
list_b = []
for i in range(4):
input_values = input("Press {}, {} and {}".format("id1", "name", "id2"))
id1, name, id2 = input_values.split()
list_a["id1"] = id1
list_a["name"] = name
list_a["id2"] = id2
list_b.append(dict(list_a))
print(list_b)
If my input is something like 1 name_ok 0, it works. But if my input is something like 1 pasta ok 0, doesn't works because 3 values are expected, not 4.
How could I do to consider that any character between the two integer values was the variable name?
Sorry about the english xD
Upvotes: 1
Views: 184
Reputation: 1618
this will work:
split = input_values.split()
id1 = int(split[0])
id2 = int(split[-1])
name = " ".join(split[1:-1])
Upvotes: 1
Reputation: 25
you could use python's slicing notation for this
input_values = input("Press {}, o {} e o {}".format("id1", "name", "id2"))
listSplit = input_values.split()
id1 = listSplit[0]
name = join(listSplit[1:-1])
id2 = listSplit[-1]
def join(arr):
newStr = ""
for i in arr:
newStr += i + " "
return newStr[:-1]
where id1 is the first word, name is everything between the first index and the last which has been joined into one string and the third argument which is actually the last word.
Hope that helps.
Upvotes: 1
Reputation: 532023
You don't necessarily know that id2
is the third argument; it's the last argument. You can gather all the intervening arguments into a single tuple using extended iterable unpacking. Once you have the tuple of middle arguments, you can join them back together.
id1, *names, id2 = input_valores.split()
list_a["id1"] = int(id1)
list_a["name"] = " ".join(names)
list_a["id2"] = int(id2)
This is somewhat lossy, as it contracts arbitrary whitespace in the name down to a single space; you get the same result of 1
, "foo bar"
, and 2
from "1 foo bar 2"
and "1 foo bar 2"
, for instance. If that matters, you can use split twice:
# This is the technique alluded to in Ignacio Vazquez-Abrams' comment.
id1, rest = input_valores.split(None, 1)
name, id2 = rest.rsplit(None, 1)
rsplit
is like split
, but starts at the other end. In both cases, the None
argument specifies the default splitting behavior (arbitrary whitespace), and the argument 1
limits the result to a single split. As a result, on the first and last space is used for splitting; the intermediate spaces are preserved.
Upvotes: 2
Reputation: 109686
You can use slicing.
args = input('Enter ID, name, and second ID').split()
id1 = int(args[0])
id2 = int(args[-1])
name = " ".join(args[1:-1])
Upvotes: 2