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

filter hyperlinks - python
Get movie information from IMDb API website
super() method resolution in python
i need to add time to the python key logger [duplicate]
Python and regex to find a number of length 5
Django REST same API for different countries
How to pass boost::none to Python Quantlib
How to get list from list of list of tuples in python
How can I distribute my python desktop application?
How to load images and labels to image_data_layer using Python?
Getting the connected components in a graph
Flask hangs after importing pandas (also numpy, matplotlib etc.)
saving pandas dataframe as hdf5
Odoo 9 | search Product by categories in website search
conda 32-bit keep installing 64-bit python 3.5.2
xpath with lxml for Python to get data

Categories

HOME
plsql
nuxeo
agile
jbehave
google-sheets-api
laravel-5.2
windows-store-apps
couchdb-2.0
spring-cloud-contract
google-spreadsheet-api
structuremap
diagram
vuex
xamarin-studio
gatsby
image-recognition
ctypes
ida
spring-cloud-config
jcl
internet-explorer-8
tarantool
visual-c++-2017
geopandas
spring-data-neo4j
owl-api
bitcoin-testnet
cell-array
apache-cloudstack
expand
swiftcharts
geopy
salesforce-chatter
rhel.net
parse-android-sdk
dql
rule
lexical-analysis
intellij-idea-2016
tripwire
intersystems-ensemble
rich-text-editor
fqdn
appstore-approval
tiddlywiki
windows-95
crystal-reports-8.5
infinite-scroll
search-box
payu
glkit
vst
slam-algorithm
excon
webkit2
coordinate-transformation
mpeg-4
void
sonarqube5.3
mirrorlink
registrykey
fabric-twitter
graphical-logo
python-ggplot
docopt
method-overriding
argument-passing
colt
flash-cc
java.util.date
sslexception
iconv
qsqltablemodel
javascriptserializer
hibernate3
point-sprites
msgbox
nemerle
server-error
pivotal-crm
asp.net-routing
multibyte-functions
integer-promotion
dirty-data
castle-validators

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App