失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > python字符串str拼接

python字符串str拼接

时间:2022-12-23 06:11:52

相关推荐

python字符串str拼接

python字符串str拼接

简单粗暴地+拼接,必须是str

str01 = "hello "str02 = "world!"str03 = str01 + str02print(str03)# hello world!

用,拼接这样出来的是个元组

str04 = str01, str02print(str04)# ('hello ', 'world!') 这样拼接出来的是个元组

使用%拼接

str1 = "hello"str2 = "world"print("%s,%s" % (str1, str2))# hello,world

使用.format拼接

str1 = "hello {}! my name is {}.".format('world', 'python')print(str1)# hello world! my name is python.str2 = "hello {1}! my name is {0}.".format('python', 'world')print(str2)# hello world! my name is python.str3 = "hello {hello}! my name is {name}.".format(hello="world", name="python")print(str3)# hello world! my name is python.

将列表中的元素使用.join拼接

list1 = ['hello', 'world']str_join1 = ' '.join(list1)str_join2 = '-'.join(list1)print(str_join1)print(str_join2)# hello world# hello-world

使用f-string方式拼接

hello = "world"name = "python"str4 = f'Hello {hello}. my name is {name}'print(str4)# Hello world. my name is python

字典中key,value拼接成字符串

dict1 = {'key1': '001', 'key2': '002'}str_key = ','.join(dict1)str_value = ','.join(dict1.values())print(str_key, str_value)# key1,key2 001,002

() 类似元组方式拼接

str05 = ('hello'''' ''world')print(str05)# hello world

面向对象模板拼接

from string import Templatestr06 = Template('${s1} ${s2}!')print(str06.safe_substitute(s1="hello", s2="world"))# hello world!

如果觉得《python字符串str拼接》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。