简体   繁体   中英

How to read user command input and store parts in variables

So let's say that user types !give_money user#5435 33000

Now I want to take that user#5435 and 33000 and store them in variables.

How do I do that? Maybe it is very simple but I don't know.

If you need any more info please comment.

Thanks!

list_of_sub_string=YourString.split()
print(list_of_sub_string[-1])  #33000
print(list_of_sub_string[-2])  #user#5435

Split the input on spaces and extract the second and third elements:

parts = input().split()
user = parts[1]
numb = parts[2]

Although it would be more Pythonic to unpack into variables (discarding the first with a conventional underscore):

_, user, numb = input().split()

Just to elaborate further, input.split() returns a list of the sublists split at the deliminator passed into the function. However, when there are no inputs, the string is split on spaces.

To get a feel, observe:

>>> 'hello there bob'.split()
['hello', 'there', 'bob']
>>> 'split,on,commas'.split(',')
['split', 'on', 'commas']

and then unpacking just assigns variables to each element in a list:

>>> a, b, c = [1, 2, 3]
>>> a
1
>>> b
2
>>> c
3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM