In this tutorial, we will learn how to convert python String to int and int to String in python. In our previous tutorial we learned about Python List append function.

在本教程中,我们将学习如何在python中将python String转换为int以及将int转换为String。 在上一教程中,我们了解了Python List附加函数。

将Python字符串转换为Int (Python String to Int)

If you read our previous tutorials, you may notice that at some time we used this conversion. Actually, this is necessary in many cases. For example, you are reading some data from a file, then it will be in String format and you will have to convert String to an int.

如果您阅读了以前的教程,您可能会注意到有时我们使用了这种转换。 实际上,在许多情况下这是必要的。 例如,您正在从文件中读取某些数据,那么它将采用String格式,则必须将String转换为int。

Now, we will go straight to the code. If you want to convert a number that is represented in the string to int, you have to use int() function to do so. See the following example:

现在,我们将直接进入代码。 如果要将字符串中表示的数字转换为int,则必须使用int()函数。 请参见以下示例:

num = '123'  # string data# print the typeprint('Type of num is :', type(num))# convert using int()num = int(num)# print the type againprint('Now, type of num is :', type(num))

The output of the following code will be

以下代码的输出将是

Type of num is : <class 'str'>
Now, type of num is : <class 'int'>

Python String To Int

将Python字符串转换为Int

从不同的基础将String转换为int (Converting String to int from different base)

If the string you want to convert into int belongs to different number base other that base 10, you can specify the base for conversion. But remember that the output integer is always in base 10. Another thing you need to remember is that the given base must be in between 2 to 36. See the following example to understand the conversion of string to int with the base argument.

如果要转换为int的字符串属于不同于10的数字基数,则可以指定转换的基数。 但是请记住,输出整数始终以10为底。您需要记住的另一件事是,给定的底数必须在2到36之间。请参见以下示例,以了解使用base参数将字符串转换为int的情况。

num = '123'
# print the original string
print('The original string :', num)# considering '123' be in base 10, convert it to base 10print('Base 10 to base 10:', int(num))# considering '123' be in base 8, convert it to base 10print('Base 8 to base 10 :', int(num, base=8))# considering '123' be in base 6, convert it to base 10print('Base 6 to base 10 :', int(num, base=6))

The output of the following code will be

以下代码的输出将是

Python Convert String To Int With Base

Python使用基数将字符串转换为Int

将String转换为int时发生ValueError (ValueError when converting String to int)

While converting from string to int you may get ValueError exception. This exception occurs if the string you want to convert does not represent any numbers.

从字符串转换为int时,您可能会遇到ValueError 异常 。 如果要转换的字符串不代表任何数字,则会发生此异常。

Suppose, you want to convert a hexadecimal number to an integer. But you did not pass argument base=16 in the int() function. It will raise a ValueError exception if there is any digit that does not belong to the decimal number system. The following example will illustrate this exception while converting a string to int.

假设您要将十六进制数转换为整数。 但是您没有在int()函数中传递参数base = 16 。 如果有任何数字不属于十进制数字系统,它将引发ValueError异常。 下面的示例将说明在将字符串转换为int时发生的异常。

"""Scenario 1: The interpreter will not raise any exception but you get wrong data
"""
num = '12'  # this is a hexadecimal value# the variable is considered as decimal value during conversion
print('The value is :', int(num))# the variable is considered as hexadecimal value during conversion
print('Actual value is :', int(num, base=16))"""Scenario 2: The interpreter will raise ValueError exception
"""num = '1e'  # this is a hexadecimal value# the variable is considered as hexadecimal value during conversion
print('Actual value of \'1e\' is :', int(num, base=16))# the variable is considered as decimal value during conversion
print('The value is :', int(num))  # this will raise exception

The output of the above code will be:

上面代码的输出将是:

The value is : 12
Actual value is : 18
Actual value of '1e' is : 30
Traceback (most recent call last):File "/home/imtiaz/Desktop/str2int_exception.py", line 22, in print('The value is :', int(num))  # this will raise exception
ValueError: invalid literal for int() with base 10: '1e'

Python String To Int ValueError

Python字符串转换为ValueError

Python int转换为String (Python int to String)

Converting an int to string requires no effort or checking. You just use str() function to do the conversion. See the following example.

将int转换为字符串无需费力或检查。 您只需使用str()函数进行转换。 请参见以下示例。

hexadecimalValue = 0x1effprint('Type of hexadecimalValue :', type(hexadecimalValue))hexadecimalValue = str(hexadecimalValue)print('Type of hexadecimalValue now :', type(hexadecimalValue))

The output of the following code will be:

以下代码的输出将是:

Type of hexadecimalValue : <class 'int'>
Type of hexadecimalValue now : <class 'str'>

Python Int To String Conversion

Python Int到字符串的转换

That’s all about Python convert String to int and int to string conversion.

这就是关于Python将String转换为int以及将int转换为字符串的全部内容。

Reference: Python Official Doc

参考: Python官方文档

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

将Python字符串转换为Int,将Int转换为String相关推荐

  1. python字符串函数的find方法_Python string模块 字符串函数方法操作教程

    我们在Python编程过程中,经常会处理一些字符串的相关操作,例如:查找.替换.分隔.截取以及英文的大小写转换等,这个时候Python程序员首选的一定是 string模块 . 一.string模块简单 ...

  2. python 字符串首字母_如何将string(Python)中每个单词的首字母大写?

    以下是不同方式的总结: 最简单的解决scheme是将句子拆分为单词,并将第一个字母大写,然后将其连接在一起. # Be careful with multiple spaces, and empty ...

  3. 【转载】 C#中使用int.TryParse方法将字符串转换为整型Int类型

    在C#编程过程中,将字符串string转换为整型int过程中,时常使用的转换方法为int.Parse方法,但int.Parse在无法转换的时候,会抛出程序异常,其实还有个int.TryParse方法可 ...

  4. java int.tryparse_【转载】 C#中使用int.TryParse方法将字符串转换为整型Int类型

    在C#编程过程中,将字符串string转换为整型int过程中,时常使用的转换方法为int.Parse方法,但int.Parse在无法转换的时候,会抛出程序异常,其实还有个int.TryParse方法可 ...

  5. c语言int转换为十六进制,C语言将int型数据转换为十六进制的字符串

    方法一: int i =0; char * inttohex(int aa,char *buffer) { if (aa < 16) //递归结束条件 { if (aa < 10) //当 ...

  6. python字符串小数转化整数_python – Pandas将字符串列和NaN(浮点数)转换为整数,保持NaN...

    参见英文答案 > Convert Pandas column containing NaNs to dtype `int`                                     ...

  7. python数字转字符串_python如何将字符转换为数字

    int(x [,base ])         将x转换为一个整数 long(x [,base ])        将x转换为一个长整数 float(x )             将x转换到一个浮点 ...

  8. python 字符串排序 偶数位交换_在Python中将字符串列表转换为整数排序列表

    当我们必须处理以字符串表示的数字时,使用python分析数据可以为我们带来情景.在本文中,我们将获取一个列表,其中包含以字符串形式出现的数字,我们需要将其转换为整数,然后以排序方式表示它们. 带图和排 ...

  9. python字符串转换成数字_python如何将字符转换为数字

    python中的字符数字之间的转换函数int(x [,base ]) 将x转换为一个整数 long(x [,base ]) 将x转换为一个长整数 float(x ) 将x转换到一个浮点数 comple ...

最新文章

  1. JavaScript和HTML实现的简单计算机
  2. VS.NET2005中的WEBPART初步(二)
  3. LeetCode 501. 二叉搜索树中的众数(中序遍历)
  4. python写一个crm系统_用Python打造一个CRM系统(四)
  5. db2 表添加字段及注释操作
  6. JavaScript—获取参数(23)
  7. idea快捷键最全最新最好
  8. XSS fuzzing 工具
  9. 参加百度开放云编程马拉松后一点总结
  10. Android之 APP创建或删除快捷方式
  11. 2018 年计算机语言排行榜,TIOBE:2018年11月编程语言排行榜
  12. 3dmax2014 uv用法_3dmax2014UVW是什么意思,怎么展开UVWID:30075914
  13. java 开发工具eli_二进制开发ELI5 –第1部分
  14. 迅捷路由器设置AP模式
  15. 【npm】tunneling socket could not be established
  16. 地图学相关知识(一)
  17. Quartz - Java 任务调度
  18. 组合数学(洛谷P5148)
  19. 方程组通解的参数向量形式、基本变量和自由变量
  20. spring cloud是什么时候流行的_老司机给我们解读 Spring Boot 最流行的 16 条实践 - 码农突围

热门文章

  1. 昆特牌Online——客户端用到的一些技术
  2. codeforces 414C C. Mashmokh and Reverse Operation(归并排序求逆序对)
  3. 发布后500访问错误 —— dll引用错误
  4. Linux strace命令 一
  5. 连接Oracle9i,因字符集造成乱码的解决方法
  6. [转载] python基础知识三——try与except处理异常语句
  7. [转载] python difference用法_set.difference() 的用法(python3)_举例说明python3 set方法功能
  8. [转载] sklearn FutureWarning: numpy not_equal will not check..., The comparison did not return the sam
  9. [转载] 50个数据可视化最有价值的图表(附完整Python代码,建议收藏)
  10. python实现:用类实现一个图书馆,实现借书,入库,还书,查书,等功能,要求数据可以保存到文件中,退出后下次可以找回数据...