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
函数获得。

转换为浮动(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)

检查转换后的数字类型(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)

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