python 添加字符串的七种方法

#使用{}的方法
s1 = 'Hello {}! My name is {}.'.format('World', 'Python猫')
print(s1)

s2 = 'Hello {0} My name is {1}.'.format('world','Python 猫')
print(s2)

s3 = 'Hello {name1}! My name is {name2}.'.format(name1='world',name2='Python 猫')
print(s3)

#使用 % 的方法
print('%s %s' % ('Hello', 'world'))

#使用()类似元组的方法
s_tuple = ('Hello',' ','world')
s_like_tuple = ('Hello' ' ' 'world')

print(s_tuple)
print(s_like_tuple)
type(s_like_tuple)

#面向对象模板拼接
from string import Template
s = Template('${s1} ${s2}!')
print(s.safe_substitute(s1='Hello',s2='world'))

#+号方式
str_1 = 'Hello world!  '
str_2 = 'My name is Python猫.'
print(str_1 + str_2)
print(str_1)

#join()拼接方式
str_list = ['Hello','wordl']
str_join1 = ''.join(str_list)
str_join2 = '-'.join(str_list)
print(str_join1)
print(str_join2)

#f-string
name = 'world'
myname = 'python_cat'
words = f'Hello {name}. My name is {myname}.'

 

posted @ 2018-12-14 23:02  萧白白  阅读(32324)  评论(0编辑  收藏  举报