python笔记-字符串连接

本文介绍了字符串连接的不同方式,包括使用加号、join方法和format函数,并对比了它们在不同场景下的性能表现。此外还展示了字符串与列表之间的转换方法。

 

字符串连接

+

   1.Java中其他基本数据类型和string+,自动转成string处理

  Python中没有此特性。需要先转成string再做拼接

  2.每连接一次,就要重新开辟空间,然后把字符串连接起来,再放入新的空间

    大量字符串拼接时,效率低

join

   'sep'.join(seq) ,seq必须是一个list,元组

   上面的语法即:以sep作为分隔符,将seq字符串序列中所有的元素合并成一个新的字符串

 

  *加号连接效率低是在连续进行多个字符串连接的时候出现的,如果连接的个数较少,加号连接效率反而比join连接效率高

format

str.format(text) 

str中包含占位符,text中是要填充的内容

使用'{}'占位符

使用'{0}','{1}'形式的占位符

使用'{name}'形式的占位符

1 protocol='http'
2 domain ='192.168.2.111'
3 url = 'huice/event/api/add'
4 data ="title='python大会'&time='2018-01-06'"
5 print(protocol+'://' + domain + '/' + url + '/' + data)  # 使用加号连接字符串
6 print("{0}://{1}/{2}/{3}".format(protocol,domain,url,data))    # 使用str.format(text) 格式化输出

#打印结果:
http://192.168.2.111/huice/event/api/add/title='python大会'&time='2018-01-06'
http://192.168.2.111/huice/event/api/add/title='python大会'&time='2018-01-06'

case='case01' desc='测试用例一' data='id=1' method ="""def test_{case}(self): {desc} execute_case({data}) """ method = method.format(case=case,desc=desc,data=data) print(method) # 打印结果: def test_case01(self): 测试用例一 execute_case(id=1) a=("2018","12","25") print('/'.join(a)) # 使用指定字符连接字符串 # 打印结果:2018/12/25

 

字符串转列表

str1 = "hi hello world"
print(str1.split(" "))
输出:
['hi', 'hello', 'world']

 

2. 列表转字符串

l = ["hi","hello","world"]
print(" ".join(l))
输出:
hi hello world

 

转载于:https://www.cnblogs.com/lily1989/p/8462548.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值