如何将Python字符串转换为Int?

Python has different variable types. Integer and string types are the most used types. And the conversation between them is required most of the time. In this post, we will look at howto convert string to int?

Python具有不同的变量类型。 整数和字符串类型是最常用的类型。 他们之间的对话大部分时间都是必需的。 在本文中,我们将研究如何将字符串转换为int?

字符串类型 (String Types)

The string is character array-like text data. Following examples are all string

该字符串是类似于字符数组的文本数据。 以下示例均为字符串

a="t" 
b="this" 
c="this too" 
d="1" 
e="1,5"

All of the above definitions are a string but they hold different or numeric characters. An integer is a base type for python. An integer is actually an umbrella definition.

以上所有定义都是字符串,但它们包含不同或数字字符。 整数是python的基本类型。 整数实际上是一个伞形定义。

将单个字符串值转换为整数 (Convert Single String Value to Integer)

We will convert a single string variable value into an integer by using int function provided python.

我们将使用python提供的int函数将单个字符串变量值转换为整数。

d="1"    
i=int(d)

Type of the new variable can get with with type function.

新变量的类型可以通过type函数获得。

《如何将Python字符串转换为Int?》 Convert Single String Value to Integer 将单个字符串值转换为整数

转换为浮动(Convert To Float)

A string can be converted to float too. Float provides more precision on the numeric type. In this example, we will convert 1.5 into the float. As float provides floating numbers.

字符串也可以转换为浮点数。 浮点数为数字类型提供了更高的精度。 在此示例中,我们将1.5转换为float。 由于float提供了浮点数。

d="1.5" 
f=float(d)

《如何将Python字符串转换为Int?》 Convert To Float 转换为浮动

检查转换后的数字类型(Check Converted Number Type)

We have already seen how to check the converted number types. But I just wanted to show this explicitly. Python programming language provides type() function which is used to check given variable type and print as type. In this example, we will check the type of variable str which is a string.

我们已经看到了如何检查转换后的数字类型。 但是我只是想明确地显示这一点。 Python编程语言提供了type()函数,该函数用于检查给定的变量类型并打印为类型。 在这个例子中,我们将检查变量str的类型,它是一个字符串。

str="poftut.com" 
type(str)

《如何将Python字符串转换为Int?》 Check Converted Number Type 检查转换后的数字类型
LEARN MORE  Introduction to Javascript Programming Language 了解更多Javascript编程语言简介

翻译自: https://www.poftut.com/python-string-to-int/

    原文作者:cunjiu9486
    原文地址: https://blog.csdn.net/cunjiu9486/article/details/109073216
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞