python 连接字符串和int

时间:2020-02-23 14:42:33  来源:igfitidea点击:

本教程指导如何在Python中连接字符串和int

在其他语言,如Java,C++等,我们可以使用+运算符连接字符串和int,但在Python中不能这样做。

如何在Python中连接字符串和int

让我们首先尝试使用 +运算符连接字符串和int。

strOne = "one"
intOne = 1
strInt = strOne + intOne
print(strInt)

输出:

--------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-7b8584e65471> in <module>
      1 strOne = "one"
      2 intOne = 1
----> 3 strInt = strOne + intOne
      4 print(strInt)
 
TypeError: can only concatenate str (not "int") to str

有多种方法可以在Python中连接字符串和int。

使用str()

使用str()函数将Intone转换为str的最佳方法。
这是一个例子。

strOne = "one"
intOne = 1
strInt = strOne + str(intOne)
print(strInt)

使用format()

你也可以使用 format()函数连接字符串和int。
这是一个例子。

strTwo = "two"
intTwo = 2
strInt = "{}{}".format(strTwo,intTwo)
print(strInt)

输出:

two2

使用%运算符

你也可以使用 %运算符连接字符串和int。
这是一个例子。

strThree = "three"
intThree = 3
strInt = "%s%s"%(strThree,intThree)
print(strInt)

输出:

three3

使用ROP()运算符 repr()提供对象的可打印表示。

这是一个例子。

strSix = "Six"
intSix = 6
strInt = strSix + repr(intSix)
print(strInt)

输出:

Six6

使用f字符串

我们还可以使用F字符串运算符将字符串和int从Python 3.6开始连接到。
这是一个例子。

strFour = "four"
intFour = 4
strInt = f'{strFour}{intFour}'
print(strInt)

输出:

four4

打印字符串和int

如果我们只想一起打印字符串和int,可以使用 print()和 `sep=""" 。
这是一个例子。

strFive = "Five"
intFive = 5
print(strFive,intFive, sep="")

输出:

Five5

为什么我们不能使用+运算符来连接字符串和int

在Python, +可用于添加两个数字或者连接序列。

通常,Python不在使用运算符的同时将对象隐式转换为另一个对象,因此可能会令我们想到的是究竟是令人困惑的 +运算符。

2 +'3'可以是'23'或者5,因此Python不支持+运算符来连接字符串和int。

我们不能在Python中使用+运算符连接不同类型的序列。

list1 =[1,2,3] + {5,6,7}

输出:

--------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-17-ff3ed0939f93> in <module>
----> 1 list1 =[1,2,3] + {5,6,7}
 
TypeError: can only concatenate list (not "set") to list