在python中连接字符串和整数

问题:在python中连接字符串和整数

用python说你有

s = "string"
i = 0
print s+i

会给你错误,所以你写

print s+str(i) 

不会出错。

我认为这是处理int和字符串连接的笨拙方式。甚至Java也不需要显式转换为String来进行这种连接。有没有更好的方法来进行这种串联,即在Python中无需显式转换?

In python say you have

s = "string"
i = 0
print s+i

will give you error so you write

print s+str(i) 

to not get error.

I think this is quite a clumsy way to handle int and string concatenation. Even Java does not need explicit casting to String to do this sort of concatenation. Is there a better way to do this sort of concatenation i.e without explicit casting in Python?


回答 0

现代字符串格式:

"{} and {}".format("string", 1)

Modern string formatting:

"{} and {}".format("string", 1)

回答 1

没有字符串格式:

>> print 'Foo',0
Foo 0

No string formatting:

>> print 'Foo',0
Foo 0

回答 2

使用新样式.format()方法(默认使用.format()提供)进行字符串格式化:

 '{}{}'.format(s, i)

或更旧的,但“仍然存在”,- %格式化:

 '%s%d' %(s, i)

在以上两个示例中,串联的两个项目之间没有空格。如果需要空间,可以简单地将其添加到格式字符串中。

这些提供了 如何串联项目,它们之间的空间等很多控制和灵活性。有关的详细信息格式规范的请参见此

String formatting, using the new-style .format() method (with the defaults .format() provides):

 '{}{}'.format(s, i)

Or the older, but “still sticking around”, %-formatting:

 '%s%d' %(s, i)

In both examples above there’s no space between the two items concatenated. If space is needed, it can simply be added in the format strings.

These provide a lot of control and flexibility about how to concatenate items, the space between them etc. For details about format specifications see this.


回答 3

Python是一种有趣的语言,尽管通常有一种(或两种)“显而易见”的方式来完成任何给定的任务,但灵活性仍然存在。

s = "string"
i = 0

print (s + repr(i))

上面的代码段使用Python3语法编写,但始终允许打印后的括号(可选),直到版本3强制使用为止。

希望这可以帮助。

凯特琳

Python is an interesting language in that while there is usually one (or two) “obvious” ways to accomplish any given task, flexibility still exists.

s = "string"
i = 0

print (s + repr(i))

The above code snippet is written in Python3 syntax but the parentheses after print were always allowed (optional) until version 3 made them mandatory.

Hope this helps.

Caitlin


回答 4

format()方法可用于连接字符串和整数

print(s+"{}".format(i))

format() method can be used to concatenate string and integer

print(s+"{}".format(i))

回答 5

如果您只想打印哟,可以这样做:

print(s , i)

if you only want to print yo can do this:

print(s , i)

回答 6

在python 3.6及更高版本中,您可以像这样格式化它:

new_string = f'{s} {i}'
print(new_string)

要不就:

print(f'{s} {i}')

in python 3.6 and newer, you can format it just like this:

new_string = f'{s} {i}'
print(new_string)

or just:

print(f'{s} {i}')