Python int 到 string 转换
最后修改于 2024 年 1 月 29 日
Python int 到 string 教程展示了如何将整数转换为字符串。我们可以使用 str 函数和字符串格式化进行转换。
整数到字符串转换是一种类型转换或类型强制转换,其中将整数数据类型的实体更改为字符串类型。
Python str 函数
内置的 str
函数返回给定对象的字符串版本。
>>> str(2) '2' >>> str(3.3) '3.3' >>> str(True) 'True'
Python 是强类型
Python 是一种动态强类型编程语言。动态编程语言,包括 Python、Ruby 和 Perl,不会在代码中显式指定数据类型。
强类型语言在执行操作时需要严格的规则。弱类型语言,如 Perl 或 JavaScript,会执行自动转换。
simple.py
#!/usr/bin/python n = 3 msg = 'There are ' + n + ' falcons in the sky' print(msg)
在此示例中,我们将字符串和整数连接起来。
$ ./simple.py Traceback (most recent call last): File "/root/Documents/prog/python/int2str/./strongly_typed.py", line 5, in <module> msg = 'There are ' + n + ' falcons in the sky' TypeError: can only concatenate str (not "int") to str
我们收到一条错误消息,因为 Python 要求 +
运算符的所有操作数都是字符串。
simple2.py
#!/usr/bin/python n = 3 msg = 'There are ' + str(n) + ' falcons in the sky' print(msg)
我们使用 str
函数将 n
变量的数据类型更改为字符串。
$ ./simple2.py There are 3 falcons in the sky
现在程序运行正常。
simple.pl
#!/usr/bin/perl use 5.30.0; use warnings; my $n = 3; say 'There are ' . $n . ' falcons in the sky';
Perl 也是一种动态语言,但与 Python 不同,它是一种弱类型语言。这意味着 Perl 会自动进行适当的类型转换。
$ ./simple.pl There are 3 falcons in the sky
使用格式化进行 Python int 到 string 转换
我们可以使用 Python 提供的各种格式化选项进行转换。这通常是一种更自然的方法。
use_format.py
#!/usr/bin/python val = input('enter a value: ') print(f'You have entered {val}')
在此示例中,我们使用 input
函数向用户请求一个值。然后使用 Python 的 fstring 将该值添加到消息中。
$ ./use_format.py enter a value: 5 You have entered 5
在本文中,我们展示了如何在 Python 中执行 int 到 string 的转换。
来源
作者
列出所有 Python 教程。