在Python中,字符串是一种常用的数据类型。对字符串的定义及表达方式有了了解后,接下来的学习,将为大家讲解如何使用Python来实现字符串的拼接。

1.加号拼接
s = “Hello” + ” ” + “world” + ” I” print(s)
</pre> 输出结果: <img class="aligncenter size-full wp-image-11377" src="https://www.python51.com/wp-content/uploads/2021/04/1603417207799883.png" width="732" height="123" /> 2. ( ) 拼接 liststr = [‘Hello’,’World’,’I’] strlist = ”.join(liststr) print(‘转换后的数据类型是:’,type(strlist)) print(‘转换后的数据是:’,strlist) <pre class="brush:js;toolbar:false">
输出结果:

3. 操作符拼接
s = “{} {}”.format(‘Hello’,’World’) print(‘输出结果是:’,s) s1 = “{0} {1}”.format(‘Hello’,’world’) print(‘s1的结果是 {}’.format(s1)) s2 = “{a} {b}”.format(a=’Hello’,b=’world’) print(‘s2的结果是 {}’.format(s2))
</pre> 输出结果: <img class="aligncenter size-full wp-image-11382" src="https://www.python51.com/wp-content/uploads/2021/04/1603417313248658.png" width="734" height="136" /> 4.(%)操作符进行拼接 s = “%s %s “%(‘Hello’,’world’) print(s) <pre class="brush:js;toolbar:false">
输出结果:

5.通过()进行拼接
s=( ‘hello’ + ‘\n’ ” ‘World’ + ‘\n’ ‘!’ ) print(s)
</pre>
输出结果:
<img class="aligncenter size-full wp-image-11389" src="https://www.python51.com/wp-content/uploads/2021/04/1603417418855627.png" width="712" height="174" />
6.F-string拼接 (该方法适用于版本)
s1=”Hello” s2=”World” print(f'{s1} {s2}’)
<pre class="brush:js;toolbar:false">
在版本不兼容报错:

以上就是在Python中关于字符串拼接的几种简单方式,其他方式欢迎大家评论补充,一起携手向Python进阶迈进。
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试



