Parse string into different types
I have looked at this solution but my requirements are slightly different. I have a string of the form: "command int1 int2", e.g. "download 600 10". I know I could use str.split(" ") to break the string into its component parts but then I would have to convert the 2nd and 3rd parameters to ints. Thus the following won't work (the int cast fails when it encounters "download" in the string): (cmd, int1, int2) = [int(s) for s in file.split(' ')] I'm still pretty new to Python... so I'm wondering if there is a nice, pythonic way to accomplish my goal?
You could maps types to values: >>> types = (str, int, int) >>> string = 'download 600 10' >>> cmd, int1, int2 = [type(value) for type, value in zip(types, string.split())] >>> cmd, int1, int2 ('download', 600, 10)
It depends on your take on what "pythonic" means to you, but here's another way: words = file.split(" ") cmd, (int1, int2) = words, map(int, words[1:])
There isn't anything more Pythonic in the standard library. I suggest you just do something simple such as: cmd = file.split(' ') command = cmd arg1 = int(cmd) arg2 = int(cmd) You could always try to look for a little parser, but that would be overkill.
From here I have imported the following function, which use isdigit() (see here): def check_int(s): # check if s is a positive or negative integer if s in ('-', '+'): return s[1:].isdigit() return s.isdigit() Then you need only this code: your_string = "download 600 10" elements = your_string.split(" ") goal = [int(x) for x in elements if check_int(x)] cmd, (int1,int2) = elements, goal
You can do it like this. file = "downlaod 600 10" file_list = file.split(' ') for i in range(len(file_list)): try: file_list[i] = int(file_list[i]) except ValueError: pass (cmd, int1, int2) = file_list
Difference between pre-trained word embedding and training word embedding in keras
AttributeError: module 'xlwings' has no attribute 'save'
Images broadcast over UDP socket (Python)
Index class as list and as dictionary
Python “will the arrow fly straight program”
Processing an eventlog with Pandas - find next match in DataFrame
Intellij python plugin debugging the script copied under the target directory
Create a list with repeated values with list comprehension
Is LASSO regression implemented in Statsmodels?
There is a duplicate line showed when calling a __init__ in Python script
trouble with mousewheel + scrollbars in tkinter
Python Cutting a string on a certain point
Ansible become_user error UnicodeEncodeError: 'ascii' codec can't encode character
Dynamic way to create new columns as a function of existing columns in pandas
polymorphic dispatch: distinguishing Python integers vs. floating-point numbers vs. strings
HTCondor output files: obtain created directory