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

Convert Single String Value to Integer
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)
Convert To Float
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)
Check Converted Number Type
Check Converted Number Type
检查转换后的数字类型
LEARN MORE  Introduction to Javascript Programming Language
了解更多Javascript编程语言简介

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

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值