python字符串怎么和整数连接?

Python012

python字符串怎么和整数连接?,第1张

1、在python中完成字符串和数字的拼接,可以使用内置函数str()。

2、在python中如果直接对字符串和数字进行拼接,会发生报错

3、使用内置函数str()转换为类型。

4、使用str()对数值转化为类型之后,可以正常运行。

5、在print()中使用逗号分隔打印数据,也可以解决字符串和数值连接的问题。

python如何在循环内拼接:通过这种方式拼接字符串需要注意的是字符串中{}的数量要和format方法参数数量一致,否则会报错。

通过(%)操作符拼接

>>>'%s %s!' % ('Hello', 'World')

'Hello World!'

这种方式与str.format()使用方式基本一致。

通过()多行拼接

>>>(

... 'Hello'

... ' '

... 'World'

... '!'

... )

'Hello World!'

python遇到未闭合的小括号,自动将多行拼接为一行。

通过string模块中的Template对象拼接

>>>from string import Template

>>>s = Template('${s1} ${s2}!')

>>>s.safe_substitute(s1='Hello',s2='World')

'Hello World!'