2014-09-04 170 views
37

如果我试图做到以下几点:如何连接str和int对象?

things = 5 
print("You have " + things + " things.") 

我得到的Python 3.X以下错误:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: must be str, not int 

...并在Python 2.x的一个类似的错误:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: cannot concatenate 'str' and 'int' objects 

我该如何解决这个问题?

+7

请注意,这是打算作为一个典型答案的一个共同的问题...请除非你确定对方不要靠近重复问题有更好,更完整的答案。 – 2014-09-04 22:29:14

回答

58

这里的问题是,+操作员(至少)在Python两种不同的含义:对于数值类型,它的意思是“加数字加在一起”:

>>> 1 + 2 
3 
>>> 3.4 + 5.6 
9.0 

...和序列类型,它的意思是“串联序列”:

>>> [1, 2, 3] + [4, 5, 6] 
[1, 2, 3, 4, 5, 6] 
>>> 'abc' + 'def' 
'abcdef' 

作为一项规则,Python不隐式地从一种类型转换对象为了使操作“意义”,因为那将是令人困惑:因为in立场,你可能会认为'3' + 5应该意味着'35',但其他人可能会认为它应该意味着8甚至'8'

同样,Python将不会让您连接两个不同类型的序列:

>>> [7, 8, 9] + 'ghi' 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: can only concatenate list (not "str") to list 

正因为如此,你需要做的转换明确,你想要的是串联或增加:

>>> 'Total: ' + str(123) 
'Total: 123' 
>>> int('456') + 789 
1245 

但是,还有更好的办法。根据您所使用的Python版本,有三种不同类型的字符串格式化可,这不仅可以让你避免多个+操作:

>>> things = 5 

>>> 'You have %d things.' % things # % interpolation 
'You have 5 things.' 

>>> 'You have {} things.'.format(things) # str.format() 
'You have 5 things.' 

>>> f'You have {things} things.' # f-string (since Python 3.6) 
'You have 5 things.' 

...也让你控制值显示:

>>> value = 5 
>>> sq_root = value ** 0.5 
>>> sq_root 
2.23606797749979 

>>> 'The square root of %d is %.2f (roughly).' % (value, sq_root) 
'The square root of 5 is 2.24 (roughly).' 

>>> 'The square root of {v} is {sr:.2f} (roughly).'.format(v=value, sr=sq_root) 
'The square root of 5 is 2.24 (roughly).' 

>>> f'The square root of {value} is {sq_root:.2f} (roughly).' 
'The square root of 5 is 2.24 (roughly).' 

无论您使用% interpolationstr.format(),或f-strings取决于你:%插值已经是最长的了(对于C中的背景的人来说是熟悉的),str.format()通常更强大,而f-字符串仍然更强大(但只能在Python 3.6及更高版本中使用) 。

另一种方法是使用的事实,如果你给print多个位置参数,它会加入他们的字符串表示一起使用sep关键字参数(默认为' '):

>>> things = 5 
>>> print('you have', things, 'things.') 
you have 5 things. 
>>> print('you have', things, 'things.', sep=' ... ') 
you have ... 5 ... things. 

...但这通常不如使用Python内置的字符串格式化功能那么灵活。


虽然它使一个异常的数字类型,其中大部分人都对 '正确' 的事:

>>> 1 + 2.3 
3.3 
>>> 4.5 + (5.6+7j) 
(10.1+7j) 

实际上有四种...但template strings很少使用,有点尴尬。

+1

这个答案很好,它提供了背景信息和多种解决方案,但实际的解决方案被埋在了文本墙的中间。它将从一开始就受益于TLDR(作为[渐进披露]形式(https://en.wikipedia.org/wiki/Progressive_disclosure))。 – Helen 2016-12-29 20:10:19

+2

@ Helen这个规范Q/A有意识地写成诱饵和开关 - 这个问题有一个“gimme teh codez”风格,而答案提出了* not *立即提供了“gimme teh codez”解决方案。我不同意倒金字塔/渐进式披露方法对于初学者级别的教学是一个很好的方法;它提高了糟糕程序员的表观生产力(他们确实会“榨取”剩下的“tl”),而牺牲那些稍后维护代码的人。我宁愿帮助潜在的优秀程序员,也不愿意为可靠的程序员提供帮助,并尝试为SO做出相应贡献。 – 2016-12-29 21:22:14

+0

很好的回答。我今天学到了一些新东西。 – alpeshpandya 2017-04-05 19:21:47

-2

解决此问题的最简单方法之一(这是一个问题,不是吗?)是习惯将任何类型的对象连接到字符串使用逗号(',')作为连接运算符。这适用于print(),如果不够完美(为了避免拼接点'print()'插入的空格),只需使用下面提供的'myprint()'函数。 另一个方便的工具将是“concatByComma()”函数,其中 返回一个适当的字符串。

只要运行下面的代码,有乐趣:)

def myprint(*arg): 
    strToPrint = "" 
    for item in arg: 
     strToPrint += str(item) 
    print(strToPrint) 
def concatByComma(*arg): 
    strToPrint = "" 
    for item in arg: 
     strToPrint += str(item) 
    return strToPrint 
I = "I"; i=5 
print(I, " am " , i , " years old") 
print(('s','o', I),[' wrote','it:'],' ',{1:'hour'},'and',5," min.") 
myprint(('s','o', I),[' wrote','it:'],' ',{1:'hour'},'and',5," min.") 
+0

您可以使用print(...,sep ='')'和[str.join](https://docs.python.org/3/library/stdtypes.html#str.join )方法 – Copperfield 2017-03-31 15:42:50

-2

的Python 2.x的

  1. 'You have %d things.' % things [1]
  2. 'You have {} things.'.format(things) [2]

的Python 3.6+

  1. 'You have %d things.' % things [1]
  2. 'You have {} things.'.format(things) [2]
  3. f'You have {things} things.' [3]

参考

  1. printf-style String Formatting
  2. Built-in types -> str.format
  3. Formatted string literals
+0

这对现有答案没有任何增加。 – 2017-04-02 20:30:29

+0

@ZeroPiraeus:没有。曾听说过“可读性”? – ngub05 2017-04-07 13:13:47

+0

仅仅因为有人在我面前回答了一个问题,这并不意味着我可以用我自己的方式来接近它(我认为最能描述答案的方式)。如果你认为这是错误的,我认为这并不比错误地回答某人的回答更为错误,因为你也对同一个问题有了答案。 – ngub05 2017-04-07 13:16:37

-3

为什么就不能?

things = 5 
print("You have " + str(things) + " things.") 

这对蟒蛇2 &蟒蛇都工作3

+0

这个答案并没有增加新的东西。 – 2017-04-05 15:46:44

+0

你说得对,对不起 – 2017-04-07 14:34:21

相关问题