Python int 到字符串的转换

Pythonint到字符串教程展示了如何将整数转换为字符串。我们可以使用str函数和字符串格式来进行转换。

Python教程是Python语言的综合教程。

Integertostringconversion是一种类型转换或类型转换,将整数数据类型的实体转换为字符串一。

Pythonstr函数

内置的str函数返回给定对象的字符串版本。

>>> str(2)
'2'
>>> str(3.3)
'3.3'
>>> str(True)
'True'

Python是强类型的

Python是一种动态的强类型编程语言。动态编程语言(包括Python、Ruby和Perl)不会在代码中明确指定数据类型。

强类型语言在执行操作时需要严格的规则。Perl或JavaScript等弱类型语言执行自动转换。

#!/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要求所有操作数都是+运算符的字符串。

#!/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

现在程序运行正常。

#!/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

Pythonint转字符串带格式

我们可以使用Python提供的各种格式选项进行转换。这通常是一种更自然的方法。

#!/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到字符串的转换。

阅读Python教程或列出所有Python教程。

赞(0) 打赏

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏