Category Archives: Python

How to convert floating point numbers to integers in Python

Let’s consider you want to convert a floating point number into an integer. There are two ways of doing that.

Method 1 – Truncating

You can truncate the floating point number to just the portion before the decimal point. You can do that with the int() function which truncates the number towards zero.

>>> fpn = 57.83
>>> int(fpn)

Continue reading

How to compare strings in Python

Let’s say you want to compare two string to see if they have the same value. You can do it using the comparison operator is equal to which is represented by == (two equal signs).

>>> s1 = 'Dan'
>>> s2 = 'Dumitrache'
>>> if s1 == s2:
... print('Strings are equal!')
... else:
... print('Strings are not equal!')
Strings are not equal!

Continue reading

How to build up a large string out of smaller strings in Python

Let’s say you may want to construct a big string from smaller strings in Python. The solution is simple and it is called concatenation. As in Math, you can use the addition operator, which is +, to put one or more strings together and return a larger string.

>>> s1 = 'My name '
>>> s2 = 'is Dan.'
>>> new_string = s1 + s2
>>> print(new_string)
My name is Dan.

Continue reading