Python全系列 教程
3567个小节阅读:5929.6k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
split()可以基于指定分隔符将字符串分隔成多个子字符串(存储到列表中)。如果不指定分隔符,则默认使用空白字符(换行符/空格/制表符)。示例代码如下:
xxxxxxxxxx
>>> a = "to be or not to be"
>>> a.split()
['to', 'be', 'or', 'not', 'to', 'be']
>>> a.split('be')
['to ', ' or not to ', '']
join()的作用和split()作用刚好相反,用于将一系列子字符串连接起来。示例代码如下:
xxxxxxxxxx
>>> a = ['sxt','sxt100','sxt200']
>>> '*'.join(a)
'sxt*sxt100*sxt200'
拼接字符串要点: 使用字符串拼接符
+
,会生成新的字符串对象,因此不推荐使用+
来拼接字符串。推荐使用join
函数,因为join
函数在拼接字符串之前会计算所有字符串的长度,然后逐一拷贝,仅新建一次对象。
【操作】测试+拼接符和join(),不同的效率 (mypy_07.py)
xxxxxxxxxx
import time
time01 = time.time() #起始时刻
a = ""
for i in range(1000000):
a += "sxt"
time02 = time.time() #终止时刻
print("运算时间:"+str(time02-time01))
time03 = time.time() #起始时刻
li = []
for i in range(1000000):
li.append("sxt")
a = "".join(li)
time04 = time.time() #终止时刻
print("运算时间:"+str(time04-time03))
实时效果反馈
1. "to be or not to be".split()
,执行的结果是:
A "to be or not to be"
B ['to', 'be', 'or', 'not', 'to', 'be']
C [to, be, or, not, to, be]
D ['to be', 'or', 'not to be']
2. 使用+
和join()
拼接字符串,错误结果是:
A 字符串拼接符+
,会生成新的字符串对象
B join
函数仅新建一次对象
C +
和join()
的作用都是用来:拼接字符串
D +
和join()
效率都是一样的,用哪个都无所谓
答案
1=>B 2=>D