python


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[0], 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[0]
arg1 = int(cmd[1])
arg2 = int(cmd[2])
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[0] 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[0], 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


Related Links

how to terminate a thread which calls the webbrowser in python
Can I load HTML on Ghost.py
Combining two lists of names and sorting them to make one sorted list of names
Python equivalent of bash sort lexicographical and numerical
Why isn't my frames background showing?
Trying to do a natural join using python standard library
How to combine several querysets by key in common?
How I can speed up row column access to pandas dataframe?
Create list with combinations of 3 elements of other list with repetitions
PyQt5 does not change gifs
Pydub - combine split_on_silence with minimum length / file size
how to choose python version accordingly in pycharm?
Unable to import Flask to Kivy iOS
Unique list without spliting entries based on spaces in python
Uncaught SyntaxError: Unexpected token & error for flask and html
Django celery tasks working very long

Categories

HOME
python
pug
semantic-ui
crate
tinyos
npm
ncurses
bibtex
couchdb-2.0
is-empty
recyclerview
ll
sequelize.js
apiconnect
ipfs
spinnaker
local
activesync
arm-template
off-canvas-menu
pyephem
jogl
flexlm
plupload
cython
statusbar
hhvm
piwik
go-cd
bcrypt
npm-install
tampermonkey
kong
excel-2013
version-numbering
pitest
percentage
spring-profiles
skygear
ios-ui-automation
honeysql
css-counter
elfinder
delphi-10.1-berlin
stdclass
crop
dojox.grid.datagrid
proof
gauss
mbaas
react-native-fbsdk
fontconfig
infinite-scroll
shinyjs
pdfkit
cjson
chessboard.js
mailcatcher
gemini
post-processing
anti-cheat
asynccallback
test-class
enyo
selendroid
pyrocms
achartengine
rspec3
httpie
subversion-edge
pl-i
pgagent
left-recursion
suffix-array
sthttprequest
humanizer
planetary.js
initialization-vector
goinstant
execvp
va-list
carddav
backbone-relational
argb
vt100
tridion2009
cbcentralmanager
git-filter-branch
css-tables
javascriptserializer
wcf-web-api
shim
nsindexpath
rubycas
testunit
nvelocity
hibernate3-maven-plugin
clients
dotproject





Mobile Apps Dev
Database Users
javascript
java
csharp
php
android


MS Developer
developer works
python
ios
c
html
jquery


RDBMS discuss