用四种方法实现字符串的拼接:
- 第一种方法是每加一次,Python内部都会开辟一个新的空间用于存放,这样会造成资源的浪费和时间的消耗(不推荐使用这种方法)
- 第二种用%s进行字符串的拼接,在少量字符串拼接中是比较快的,也并不会浪费过多资源,但是拼接量过大在时间上会有劣势(少量字符串拼接建议使用这种方式)
- 第三种用join内置方法实现拼接,在少量字符串拼接时速度略差于第二种方法,如果大量的字符串拼接则优于第二种(适合大量字符串拼接)
- 第四种方法动态参数实现字符串格式化
#第一种直接相加:
def methodfirst():
en_list = ['this','is','a','sentence','!']
result = ""
for i in range(len(en_list)):
result = en_list[i] + result
print(result)
methodfirst()
#第二种方法用%s组成字符串
def methodsecond():
a = "ncwx."
b = "gcu."
c = "edu."
d = "cn"
print("website: %s%s%s%s"%(a,b,c,d))
methodsecond()
#第三种方法,用join方法实现字符串的连接
def methodththird():
name = ['w','u','l','e','i']
name_result1 = "_".join(name)
name_result2 = "".join(name)
print(name_result1)
print(name_result2)
methodththird()
#第四种方法,动态参数实现字符串格式化(元组形式)
#注释的是直接传一个元组作为实参
#没注释的是先赋值给变量,通过*(变量)的形式传入实参
def fun():
s1 = "{0}is{1}{2}"
# result = s1.format('she','very','beautiful')
# print(s1)
# print(result)
li = ('she','very','beautiful',)
other_result = s1.format(*li)
print("动态参数实现字符串格式化,元组形式:")
print(other_result)
fun()
#动态参数实现字符串格式化(字典形式)
#注释的是直接传一个元组作为实参
#没注释的是先赋值给变量,通过*(变量)的形式传入实参
def fun():
s2 ="{name}is{actor}"
# result = s2.format(name = 'Lycoridiata',actor = 'boy')
# print(result)
dic = {'name':'Lycoridiata','actor':'boy'}
other_result = s2.format(**dic)
print("动态参数实现字符串格式化,字典形式:")
print(other_result)
fun()