1. 程式人生 > >【Python】字串拼接

【Python】字串拼接

%

%號格式化字串的方式繼承自古老的C語言,這在很多程式語言都有類似的實現。上例的%s是一個佔位符,它僅代表一段字串,並不是拼接的實際內容。實際的拼接內容在一個單獨的%號後面,放在一個元組裡。

print('%s %s' % ('hello','python'))

format()

s1 = 'Hello {}! My name is {}.'.format('World', 'Python貓')
print(s1)

()

s_tuple = ('Hello', ' ', 'world')
s_like_tuple = ('Hello' ' ' 'world')

print(s_tuple) 
>>>('Hello', ' ', 'world')
print(s_like_tuple) 
>>>Hello world

type(s_like_tuple) >>>str

面向物件模板拼接

from string import Template
s = Template('${s1} ${s2}!') 
print(s.safe_substitute(s1='Hello',s2='world')) 
>>> Hello world!

+

str_1 = 'Hello world! ' 
str_2 = 'My name is Python貓.'
print(str_1 + str_2)
>>>Hello world! My name is Python貓.

join

str_list = ['Hello', 'world']
str_join1 = ' '.join(str_list)
str_join2 = '-'.join(str_list)
print(str_join1) >>>Hello world
print(str_join2) >>>Hello-world

f-string

name = 'world'
myname = 'python_cat'
words = f'Hello {name}. My name is {myname}.'
print(words)
>>> Hello world. My name is python_cat.