添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Report this

What is the reason for this report?

How To Convert Data Types in Python 3

Updated on August 20, 2021
English
How To Convert Data Types in Python 3

Introduction

data types are used to classify one particular type of data, determining the values that you can assign to the type and the operations you can perform on it. When programming, there are times we need to convert values between types in order to manipulate values in a different way. For example, we may need to concatenate numeric values with strings, or represent decimal places in numbers that were initialized as integer values.

This tutorial will guide you through converting numbers, strings, tuples and lists, as well as provide examples to help familiarize yourself with different use cases.

Prerequisites

local programming environment or for a programming environment on your server appropriate for your operating system (Ubuntu, CentOS, Debian, etc.)

Converting Number Types

number data types : integers and floating-point numbers or floats. Sometimes you are working on someone else’s code and will need to convert an integer to a float or vice versa, or you may find that you have been using an integer when what you really need is a float. Python has built-in methods to allow you to easily convert integers to floats and floats to integers.

Converting Integers to Floats

Converting Floats to Integers

Numbers Converted Through Division

division though they are not in Python 2. That is, when you divide 5 by 2, in Python 3 you will get a float for an answer (2.5):

a = 5 / 2
print(a)
Output
2.5

In Python 2, since you were dealing with two integers, you would receive an integer back as your answer, instead: 5 / 2 = 2. Read “Python 2 vs Python 3: Practical Considerations” for more information about the differences between Python 2 and Python 3.

Converting with Strings

string is a sequence of one or more characters (letters, numbers, symbols). Strings are a common form of data in computer programs, and we may need to convert strings to numbers or numbers to strings fairly often, especially when we are taking in user-generated data.

Converting Numbers to Strings

Converting Strings to Numbers

Converting to Tuples and Lists

  • list is a mutable ordered sequence of elements that is contained within square brackets [ ].
  • a tuple is an immutable ordered sequence of elements contained within parentheses ( ).
  • Converting to Tuples

    Converting to Lists

    Conclusion