python基础学习(第一天)(二)
- 字符串
#自动编号
>>> "{foo} {} {bar} {}".format(1, 2, bar=4, foo=3)
'3 1 4 2'
#手动编号
>>> "{foo} {1} {bar} {0}".format(1, 2, bar=4, foo=3)
'3 2 4 1'
#访问组成
>>> fullname = ["Alfred", "Smoketoomuch"]
>>> "Mr {name[1]}".format(name=fullname)
'Mr Smoketoomuch'
>>> tmpl = "The {mod.__name__} module defines the value {mod.pi} for π"
>>> tmpl.format(mod=math)
'The math module defines the value 3.141592653589793 for π'
>>> print("{pi!s} {pi!r} {pi!a}".format(pi="π"))
π 'π' '\u03c0'
>>> "number{a:b}".format(a=999)
'number1111100111'
>>> "number{a:f}".format(a=999)
'number999.000000'
>>> "number{a:.3f}".format(a=999)
'number999.000'
>>> "number{a:e}".format(a=999)
'number9.990000e+02'
#宽度,千分位分隔号,精度
>>> "number{a:10,.5f}".format(a=999999)
'number999,999.00000'
#0填充
>>> "number{a:020,.1f}".format(a=999999)
'number00,000,000,999,999.0'
#左对齐
>>> "number{a:<20,.1f}".format(a=999999)
'number999,999.0
#居中
>>> "number{a:^20,.1f}".format(a=999999)
'number 999,999.0 '
- 字符串方法
center() 居中,填充
join() 合并字符串列表
>>> dirs = '', 'usr', 'bin', 'env'
>>> '/'.join(dirs)
'/usr/bin/env'
>>> print('C:' + '\\'.join(dirs))
C:\usr\bin\env
title() 将字符串转换为标题格式,首字母大写
translate()将特定字符转换
>>> table=str.maketrans("a","b")#equal length
>>> "this a aa a".translate(table)
'this b bb b'
- 字典
>>> map={"hj":111,"hh":22,"rr":33}
>>> "number is{hh}".format_map(map)
'number is22'
dict()从键值对或者其它字典创建字典
copy(), copy.deepcopy()
fromkeys()从键值构造字典
>>> dict.fromkeys(['name', 'age'])
{'age': None, 'name': None}
>>> dict.fromkeys(['name', 'age'], '(unknown)')
{'age': '(unknown)', 'name': '(unknown)'}
get()
使用get来访问不存在的键时,没有引发异常,而是返回None。你可指定“默认” 值,这样将返回你指定的值而不是None。
>>> d.get('name', 'No')
'N0'
items()返回字典视图,随字典而变化,二元组列表
keys()只包含键的字典视图
setdefault()
指定的键不存在时,setdefault返回指定的值并相应地更新字典。如果指定的键 存在,就返回其值,并保持字典不变。与get一样,值是可选的;如果没有指定,默认为None。
update()用一个字典更新另一个字典
- 同时赋值以交换
>>> x,y=1,2
>>> x,y
(1, 2)
>>> x,y=y,x
>>> x,y
(2, 1)
>>> a, b, *rest = [1, 2, 3, 4]
>>> rest
[3, 4]
>>> a, *b, c = "abc"
>>> a, b, c
('a', ['b'], 'c')
- 断言assert
>>> age = -1
>>> assert 0 < age < 100, 'The age must be realistic'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError: The age must be realistic
zip() 缝合,以短的为标准,将列表结合为二元组
for index, string in enumerate(strings): #这个函数让你能够迭代索引值对,其中的索引是自动提供的
if 'xxx' in string:
strings[index] = '[censored]'
pass
if name == 'Ralph Auldus Melish':
print('Welcome!')
elif name == 'Enid':
# 还未完成……
pass
elif name == 'Bill Gates':
print('Access Denied')
- 删除变量
赋其它值;
del;删除变量名,内存会自动化删除 - exec()执行用户字符串的代码
>>> from math import sqrt
>>> scope = {} //命名空间
>>> exec('sqrt = 1', scope)
>>> sqrt(4)
2.0
>>> scope['sqrt']
1
- eval()
表达式求值
>>> eval(input("Enter an arithmetic expression: "))
Enter an arithmetic expression: 6 + 18 * 2
42