如何在Python字符串中快速拼接

817次阅读
没有评论

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

如何在Python字符串中快速拼接

1.加号拼接

s = “Hello” +  ” ” + “world” + ” I” print(s)

</pre>
输出结果:

<img loading="lazy" class="aligncenter size-full wp-image-11377" src="https://www.python51.com/wp-content/uploads/2021/04/1603417207799883.png" width="732" height="123" srcset="https://www.python51.com/wp-content/uploads/2021/04/1603417207799883.png 732w, https://www.python51.com/wp-content/uploads/2021/04/1603417207799883-240x40.png 240w, https://www.python51.com/wp-content/uploads/2021/04/1603417207799883-400x67.png 400w" sizes="(max-width: 732px) 100vw, 732px" />

2. ( ) 拼接

liststr = [‘Hello’,’World’,’I’] strlist = ”.join(liststr) print(‘转换后的数据类型是:’,type(strlist)) print(‘转换后的数据是:’,strlist)
<pre class="brush:js;toolbar:false">

输出结果:

如何在Python字符串中快速拼接

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 loading="lazy" class="aligncenter size-full wp-image-11382" src="https://www.python51.com/wp-content/uploads/2021/04/1603417313248658.png" width="734" height="136" srcset="https://www.python51.com/wp-content/uploads/2021/04/1603417313248658.png 734w, https://www.python51.com/wp-content/uploads/2021/04/1603417313248658-240x44.png 240w, https://www.python51.com/wp-content/uploads/2021/04/1603417313248658-400x74.png 400w" sizes="(max-width: 734px) 100vw, 734px" />

4.(%)操作符进行拼接

s = “%s %s “%(‘Hello’,’world’) print(s)
<pre class="brush:js;toolbar:false">

输出结果:

如何在Python字符串中快速拼接

5.通过()进行拼接

s=(    ‘hello’ + ‘\n’    ”    ‘World’ + ‘\n’    ‘!’ ) print(s)

</pre>
输出结果:

<img loading="lazy" class="aligncenter size-full wp-image-11389" src="https://www.python51.com/wp-content/uploads/2021/04/1603417418855627.png" width="712" height="174" srcset="https://www.python51.com/wp-content/uploads/2021/04/1603417418855627.png 712w, https://www.python51.com/wp-content/uploads/2021/04/1603417418855627-240x59.png 240w, https://www.python51.com/wp-content/uploads/2021/04/1603417418855627-400x98.png 400w" sizes="(max-width: 712px) 100vw, 712px" />

6.F-string拼接 (该方法适用于版本)

s1=”Hello” s2=”World” print(f'{s1} {s2}’)
<pre class="brush:js;toolbar:false">

在版本不兼容报错:

如何在Python字符串中快速拼接

以上就是在Python中关于字符串拼接的几种简单方式,其他方式欢迎大家评论补充,一起携手向Python进阶迈进。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-06-09发表,共计672字。
新手QQ群:570568346,欢迎进群讨论 Python51学习