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

How to use Python Casting

PHPz
Release: 2023-05-16 22:37:04
forward
1016 people have browsed it

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
Copy after login

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
Copy after login

Running instance

Python Casting怎么使用

Instance

String:

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

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template