Home  >  Article  >  Backend Development  >  How to use Python Casting

How to use Python Casting

PHPz
PHPzforward
2023-05-16 22:37:04860browse

Specify variable type

Sometimes you may need to specify a type for a variable. This can be done through casting. Python is an object-oriented language, so it uses classes to define data types, including their primitive types. .

Therefore, use the constructor to complete the conversion in python:

  • int() - Construct an integer from an integer literal, a floating point literal (by logarithm round down), or use a string literal representing a complete number

  • float() - Construct a floating-point number from an integer literal, a floating-point literal, or a string literal ( Provides a string representing a floating point number or an integer)

  • str() - Constructs strings from various data types, including strings, integer literals, and floating point literals

Instance

Integer:

x = int(1)   # x 将是 1
y = int(2.5) # y 将是 2
z = int("3") # z 将是 3

Run instance

Python Casting怎么使用

Instance

Floating point number:

x = float(1)     # x 将是 1.0
y = float(2.5)   # y 将是 2.5
z = float("3")   # z 将是 3.0
w = float("4.6")# w 将是 4.6

Running instance

Python Casting怎么使用

Instance

String:

x = str("S2") # x 将是 'S2'
y = str(3)    # y 将是 '3'
z = str(4.0)  # z 将是 '4.0'

Running instance

Python Casting怎么使用

The above is the detailed content of How to use Python Casting. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete