python字符串拼接技巧
1.使用f字符串
# 字符串中插入变量的值,可在前引号前加上字母f,再将要插入的变量放在花括号内。
usr_data = f'{usrname}|{pwd}' # andyli|123
message = f"info:{usr_data}===" # info:andyli|123===
2.join
# 从可迭代对象中取出多个字符串,然后按照指定的分隔符进行拼接,拼接的结果为字符串
>>> print('%'.join('hello')) # 从字符串'hello'中取出多个字符串,然后按照%作为分隔符号进行拼接
'h%e%l%l%o'
>>> print('|'.join(['tony','18','read'])) # 从列表中取出多个字符串,然后按照|作为分隔符号进行拼接
'tony|18|read'
3.print
3.1 用逗号“,”将多个字符串连接为一个元组
str1 = 'andy'
str2 = 'li'
print(str1, str2) # andy li
str3 = str1, str2
str4 = (''.join(str3))
print(str4) # andyli
3.2 直接连接字符串
print('andy' 'li') # andyli
# 字符串是不可变类型,新的字符串会独占一块新的内存,而原来的字符串保持不变。因此用“+”号效率低
3.3 format()
str6 = 'hell0, word!{1}{a},{0}{b}'.format('andy', 'bohui', b='li', a='ch')
print(str6) # hell0, word!bohuich,andyli
4.使用“+”号
# 有数字需使用str()函数转换成字符串,或在数字两侧加带引号,再进行连接
str5 = str1 + str2
print(str5) # andyli