Sunday, April 20, 2025

Python Casting, int, float, str

This is our starting point, one integer, float, and negative float:


x = 10
y = 12.25
z = -5345345.234234

print("Value of x: ", x, "Type: ", type(x))
print("Value of y: ", y, "Type: ", type(y))
print("Value of z: ", z, "Type: ", type(z))

To transfer all of them in simple integer, we will use int() function:


x = 10
y = int(12.25)
z = int(-5345345.234234)

print("Value of x: ", x, "Type: ", type(x))
print("Value of y: ", y, "Type: ", type(y))
print("Value of z: ", z, "Type: ", type(z))

Sometimes, all we need is bunch of floats:


x = float(10)
y = float(12.25)
z = float(-5345345.234234)

print("Value of x: ", x, "Type: ", type(x))
print("Value of y: ", y, "Type: ", type(y))
print("Value of z: ", z, "Type: ", type(z))

With str() function we can convert numbers to strings:


x = str(10)
y = str(12.25)
z = str(-5345345.234234)

print("Value of x: ", x, "Type: ", type(x))
print("Value of y: ", y, "Type: ", type(y))
print("Value of z: ", z, "Type: ", type(z))

When we have all strings, just concatenate them using plus (+) symbol:


x = str(10)
y = str(12.25)
z = str(-5345345.234234)

print(x + y + z)

Result:


1012.25-5345345.234234
>>> 

What a weird result. Now we can use tab as separator:


x = str(10)
y = str(12.25)
z = str(-5345345.234234)

print(x + "\t" + y + "\t" + z)

Result:


10	12.25	-5345345.234234
>>> 

In next tutorial we will learn how to extract individual characters from strings, and how to remove spaces.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...