版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
python 基础:列表,字符串
字符串
url = 'www.woaixuexi.com'
# 1. 替换
url.replace('com','cn')
print(url) # 输出 'www.woaixuexi.cn'
# 2.判断是否以某个字段开头
url.startswith('www')
# 返回 True
# 同startswith
url.endwith('.com')
# 3.查某个字段
url.find('baidu')
# 返回-1
# 4.格式化输出
aa = 10
bb = 20
print('{a}=>{b}'.format(a=aa,b=bb))
print('{}=>{}'.format(aa,bb))
print('{0}=>{1}'.format(aa,bb))
# 以上都行,但是 '{aa}=>{bb}'.format(aa,bb) 不行。
# 同样功能
print('%s=>%d' % (10,20))
# %s %d %f 字符串 整数 浮点数
列表
# 直接生成
t = ['a','b','c','d']
# list生成 只要是可遍历对象都可以通过list()生成 列表。如set() 等
t = list('abcd')
# 列表的方法
l = [1,2,3]
# 向后插入
l.append(4)
# 向后拼接
l.extend([4,5,6])
# 计数某元素
l.count(1)
# 查某元素位置
l.index(1) # 返回 0
# 按位置插入
l.insert(1, 100) # 返回 [1, 100, 2, 3, 4]。在 1 位置设为100, 1位置后的依次相后移位
# 弹出最后一个元素
l.pop()
关于字符串替换的方法实现(笔试出现过)
def do_replace(text1, text2):
text1 = list(text1)
text2 = list(text2)
index = 0
res = []
print(text1)
while index < len(text1):
if text1[index] == text2[0]:
if (index+len(text2)) <= len(text1) and text1[index:index+len(text2)] == text2:
res = text1[:index] + ['*']*len(text2) + text1[index+len(text2):]
break
else:
index += 1
else:
index +=1
return ''.join(res)
# 主要需要注意的是字符串 切片 前闭后开