python字符串str拼接

python字符串str拼接

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

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

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

str04 = str01, str02
print(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 Template

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

你可能感兴趣的:(python,python,字符串)