在学习Python(3x)的过程中,在拼接字符串的时候遇到了些问题,所以抽点时间整理一下Python 拼接字符串的几种方式。
方式1:使用加号(+)连接
使用加号连接各个变量或者元素必须是字符串类型(<class ‘str’>)
例如:
str_name1 = 'To'
str_name2 = 'ny'
str_name = str_name1 + str_name2
print(str_name)
输出结果:
方式2:使用.joiin(iterable) 拼接
print('-----------method2-----------')
list_good_night = ['晚', '上', '好', '!']
str_night = ''.join(list_good_night)
print(str_night)
str_night1 = '------>'.join(list_good_night)
print(str_night1)
dict_name = {'key1': 'value1', 'key2': 'value2'}
str_key = ','.join(dict_name)
str_value = ','.join(dict_name.values())
print(str_key)
print(str_value)
执行结果:
方式3:使用逗号(,)拼接
'''
学习中遇到问题没人解答?小编创建了一个Python学习交流QQ群:153708845
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
print('-----------method3-----------')
a, b = 'Hello', 'word'
c = a, b
print(a, b)
print(c)
print(type(c))
输出结果:
方式4:直接拼接
print('-----------method4-----------')
print('hello''python')
方式5:format 拼接
print('-----------method5-----------')
print('hello''python')
str_word = 'hello, word! {} {}'.format('张三', '李四')
print(str_word)
str_word_index0 = 'hell0, word!{0},{1}'.format('张三', '李四')
str_word_index1 = 'hell0, word!{1},{0}'.format('张三', '李四')
print(str_word_index0)
print(str_word_index1)
str_word_keyword = 'hell0, word!{a},{b}'.format(b='张三', a='李四')
print(str_word_keyword)
str_word1 = 'hell0, word!{1}{a}{0},{b}'.format('index0', 'index1', b='张三', a='李四')
print(str_word1)
str_word2 = 'hell0, word!{b}'.format(b=['eee', 'd'])
print(str_word2)
str_word3 = 'hello, word! {} {}'.format
word = str_word3('张三', '李四')
print(word)
输出结果:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)