Python语法基础笔记2

字符串 字典

1. 字符串

字符串是不可变的,元素赋值、切片赋值都是不可变的,改变只能通过创建新的字符串完成。(复杂度O(n)

使用+运算符拼接字符串会更加方便,效率也高

# 字符串设置格式:
format1 = "Hello, %s. %s Enough For Ya?"
value = ('World', 'Hot')
print(format1 % value)
# 使用format函数:
format2 = "{3} {0} {2} {1} {3} {0}".format('be', 'not', 'or', 'to')
from math import pi
print(format2)
format3 = "{name} is approximitely {value:.2f}".format(value=pi, name='\u03c0')
print(format3)
# 字符串方法:
# center:填充字符让字符串居中
print('Let the string in the center'.center(50, '$'))
# find:查找子串,找到返回第一个字符索引,找不到返回-1
title = '$$$ let us get rich now!!! $$$'
print(title.find('!!'))
print(title.find('!!', 0, 16))
# join:合并序列元素,元素必须均为字符串,数值会报错
seq = ['1', '2', '3', '4']
sep = '++'
print(sep.join(seq))     # 用前面的字符连接成字符串
# lower:返回字符串小写版本 title:首字母大写版本 upper:大写版本
print(format1.lower())
print(format1.title())
print(format1.upper())
print(format1)
# 指定宽度:数字和字母对齐方式不太一样
# 指定左对齐、右对齐和居中,可分别使用<、>和^
print("{:20}".format(3))
print("{:20}".format("Bob"))
# 指定精度
print("{pi:20.2f}".format(pi=pi))
# 替换:将指定子串都替换为另一个字符串,并返回替换后的结果
print('This is a test'.replace('is', 'eez'))
# 拆分:
print('/usr/bin/env'.split('/'))
# 删除字符串开头结尾的空白,也可以参数中指定要删除哪些字符(中间的不会删去,只会删开头结尾)
print('internal whitespace is kept '.strip())
# 替换:将第一个字符串中的每个字符都替换为第二个字符串中的相应字符
table = str.maketrans('cs', 'kz')
print('this is an incredible test'.translate(table))

运行结果如下:

对于两种字符串拼接操作,哪一种更快?

s = ''
for n in range(0, 100000):
    s += str(n)

l = []
for n in range(0, 100000):
    l.append(str(n))
 s=' '.join(l)   

如果字符串拼接的次数较少,比如range(100),那么方法一更优,因为时间复杂度精确的来说第一种是O(n),第二种是O(2n),如果拼接的次数较多,比如range(1000000),方法二稍快一些,虽然方法二会遍历两次,但是join的速度其实很快,列表append和join的开销要比字符串+=小一些。

2. 字典

字典的基本行为在很多方面都类似于序列。 

len(d)返回字典d包含的项(键—值对)数。 

d[k]返回与键k相关联的值。 

d[k] = v将值v关联到键k。 

del d[k]删除键为k的项。 

k in d检查字典d是否包含键为k的项。

即便是字典中原本没有的键,也可以给它赋值,这将在字典中创建一个新项。

表达式k in d(其中d是一个字典)查找的是键而不是值,而表达式v in l(其 中l是一个列表)查找的是值而不是索引。

# 创建字典
items = [('name', 'Gumby'), ('age', 42)]
d = dict(items)
# 或者:d = dict(name='Gumby', age=42)
# 或者直接用{}创建
print(d['name'])
# 字符串格式用于字典 format
phonebook = {'Beth': '9102', 'Alice': '2341', 'Cecil': '3258'}
print("Cecil's phone number is {Cecil}.".format_map(phonebook))
# 字典清除:clear
print(d.clear())
# 复制:这个方法执行的是浅复制, 因为值本身是原件,而非副本,改副本的值原件收到影响。深复制要用deepcopy
x = {'username': 'admin', 'machines': ['foo', 'bar', 'baz']}
y = x.copy()
dy = deepcopy(x)
y['username'] = 'mlh'
y['machines'].remove('bar')
print(y)
print(dy)
print(x)
# get:访问不到返回None
print(y.get('name'))
# item:返回一个包含所有字典项的列表
print(y.items())
# pop:获取与指定键相关联的值
print(x.pop("username"))
print(x)
# values:返回一个由字典中的值组成的字典视图,方法values返回的视图可能包含重复的值。
# update:如果当前字典包含键相同的项,就替换它。
d = { 'title': 'Python Web Site', 'url': 'http://www.python.org', 'changed': 'Mar 14 22:09:15 MET 2016' }
x = {'title': 'Python Language Website'}
d.update(x)
print(d)

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值