You need to use int(s) to convert a string or number to an integer. For testing purpose, defined a string called x='123456', run:
You may also need to use float(s) to convert a string or number to a floating point number or combination of both as follows:
int(s)
float(s)
int(float(s))
Examples
x = '123456'
Confirm the object type:
type(x)
Sample outputs:
<type 'str'>
Convert a string to an int and store it to i, run:
i = int(x) type(i)
Sample outputs:
<type 'int'>
However, the following string to int will fail:
x='123456.334' y=int(x)
Sample outputs:
ValueError Traceback (most recent call last) /home/vivek/in () ValueError: invalid literal for int() with base 10: '123456.334'
Try the following solution:
x='123456.334' y=int(float(x)) type(x) type(y) print y a='12.5' b='13.5' print( int(float(a))+ int(float(b)) )
Finally, you can also use floating point class for decimal arithmetic:
x='123.34' import decimal i=int(Decimal(x)) print(i) type(i)
Featured Articles:
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012

- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop












{ 0 comments… add one now }