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 timeout decorator
boto3 changing AWS ec2 instance state
Inputing date using Selenium/Python does not work
Opening IDLE from Terminal
IP proto field number to string
Setting all dictionary elements to 0 python
Translate curl to python [duplicate]
Setting Values Of Inherited Properties
How do I make pip install binaries to a writable path?
TensorFlow: generating a random constant
How can I organize my functions to get something like class.draw.line() instead of class.drawLine
Traceback (most recent call last): (works in trinket.io but not 3.4/2.7.11)
python : Mode of a List
How to send and receive data from flask?
Python HTTPS Login to account to scrape data, is this bad practice?
Celery, redis and ConnectionPool

Categories

HOME
webrtc
puppet
qpython3
thunderbird-addon
transparent
codeeffects
automated-tests
schemacrawler
proguard
ng-admin
criteria
flexbox
cs-cart
uiview
jacoco
spring-cloud-config
r-lavaan
android-toolbar
session-timeout
pyephem
movies
tortoisegit
fop
tarantool
rworldmap
switching
fileinfo
vertex-buffer
jboss5.x
protobuf-net
svnkit
postgresql-9.2
expand
receipt
powershell-remoting
remote-server
google-guava-cache
openshift-enterprise
ksoap
pmwiki
xamarin.uitest
alchemy.js
cross-entropy
jrules
datalog
matlab-cvst
3scale
chunked-encoding
component-pascal
pluck
photography
search-box
selenium-firefoxdriver
mercury
payu
rstudio-server
qregexp
clob
bluesnap
handlebars.java
evo
fabric-twitter
risk-analysis
criteria-api
google-plus-one
cpu-speed
dalekjs
magic-numbers
initialization-vector
xenocode
cling
carddav
apache2.2
fortran77
client-library
vt100
phpsh
transitive-closure-table
xgettext
z-machine
viewdidload
webkit-transform
mvccontrib-grid
clients
front-controller
openwysiwyg
gears
weborb
dotproject

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