I want to take a command line argument, argv[2]
, which will always be of the form split_pct=x
where x is a specified float. To clarify, here's some valid examples: split_pct=90.0
or split_pct=55.23
. For the given input, how could I extract that float?
Running Python 3.7
You want to look into type casting:
x = 1.0
y = 2*x # 2.0
z = 2/x # 2.0
x = str(1.0)
y = 2*x # TypeError: unsupported operand type(s) for /: 'int' and 'str'
z = 2/x # TypeError: unsupported operand type(s) for /: 'int' and 'str'
w = float(x) # Cast to float
y = 2*w # 2.0
z = 2/w # 2.0
More information can be found here .
To use an argument from the command line:
import sys
split_pct = sys.argv[2]
This works if your command is this:
python3 script.py first_var 90.0
Since the script name counts as sys.argv[0]
, see here for more details:
Resolved - because the string is of a standard form, we can get only the values after split_pct=
. split_pct=
is 10 chars, so
x = float(sys.argv[2][10:]
works.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.