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

Python Regular Expression Problems With Multiline Split
Remove all-zero rows in a 2D matrix [duplicate]
Calling function from outside the class in python or from another file
Atom.core not found when in virtualenv
argparse subcommand error message
IOError opening jpg in Python
Python: Looking for a specific value in array column
how to check when a user has input in python
GAE: Changing the value of one entity when another entity's value changes
Programatically Determining Bin Path
Estrange behavior reading JSON files in Python 3.3 [duplicate]
How to download pygame 3.4.1
Python Modules in Unix Command Line Programs
Application's Datapath - os.environ
Set active tab in Chrome and bring it to the front
How do I input multiple values from a single line?

Categories

HOME
google-apps-script
sas
voip
warnings
jbehave
command
vlc
recyclerview
ios10
filter
tizen-wearable-sdk
sequelize.js
shader
height
window
jboss-eap-7
google-shopping
cortex-a
hashicorp-vault
local
mod-pagespeed
alfresco-share
flat-file
jpeg2000
styles
apply
profile
iis-10
compare-and-swap
data-cleansing
continuous-deployment
codelite
owl-api
forum
referenceerror
spring-profiles
hawtio
ocs
large-data
pmwiki
declare
concrete5-5.7
restful-url
mediawiki-extensions
android-maps-v2
openweathermap
chown
udev
windows-95
mcrypt
emgu
efxclipse
excon
tomcat5
radians
pax-web
gherkin
cctray
hyperthreading
kendo-menu
mptcp
wif
calibration
sparse-file
gray-code
ibm-data-studio
shift-jis
searchkick
hg-git
consensus
low-level
google-earth-plugin
pl-i
ctrlp
kallithea
argument-passing
lumx
joox
magic-numbers
map-force
xenocode
crystal-reports-10
ksoap2
opendata
magicalrecord-2.2
windows-mobile-6
vmware-server
manage.py
symphony-cms
icsharpcode
macruby
expression-evaluation
point-sprites
testunit
noir
ihttphandler
recordset
filetime
divx





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