品易云推流 关闭
文章详情页
文章 > Python基础教程 > 用了这么久的python,这些零碎的基础知识,你还记得多少?

用了这么久的python,这些零碎的基础知识,你还记得多少?

头像

silencement

2019-07-11 16:55:392864浏览 · 0收藏 · 0评论

python内置的数据类型

ae014ad184dff94e8462e34f9ff8c69.png

Python3.7内置的关键字

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 
'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda',
 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

格式化输出

A = 'dog'
print('It is a %s' % A ) # --> It is a dog
# 格式符可以是 %d整数 %f浮点数
print('%06d'% 1111) #-->001111 # 拿0补全6位,不写0就是拿空格补全6位
print('%.3f' %1.2) #-->1.200 # 保留3位小数
print('It is a {}'.format(A) ) # --> It is a dog

关于format函数还可以设置参数,传递对象:format多种用法

逻辑运算符优先级and or not

当not和and及or在一起运算时,优先级为是not>and>or

字符串常见操作

find

检测 str 是否包含在 mystr中,如果是返回开始的索引值,否则返回-1

mystr.find(str, start=0, end=len(mystr))

index

跟find()方法一样,只不过如果str不在 mystr中会报一个异常.

mystr.index(str, start=0, end=len(mystr))

count

返回 str在start和end之间 在 mystr里面出现的次数

mystr.count(str, start=0, end=len(mystr))

replace

把 mystr 中的 str1 替换成 str2,如果 count 指定,则替换不超过 count 次.

mystr.replace(str1, str2, mystr.count(str1))

split

以 str 为分隔符切片 mystr,如果 maxsplit有指定值,则仅分隔 maxsplit 个子字符串

mystr.split(str=" ", 2)

capitalize

把字符串的第一个字符大写

mystr.capitalize()

title

把字符串的每个单词首字母大写

>>> a = "hello world"
>>> a.title()
'Hello world'

startswith

检查字符串是否是以 hello 开头, 是则返回 True,否则返回 False

mystr.startswith(hello)

endswith

检查字符串是否以obj结束,如果是返回True,否则返回 False.

mystr.endswith('.jpg')

lower

转换 mystr 中所有大写字符为小写

mystr.lower()

upper

转换 mystr 中的小写字母为大写

mystr.upper()

ljust

返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串

mystr.ljust(width)

rjust

返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串

mystr.rjust(width)

center

返回一个原字符串居中,并使用空格填充至长度 width 的新字符串

mystr.center(width)

lstrip

删除 mystr 左边的空白字符

mystr.lstrip()

rstrip

删除 mystr 字符串末尾的空白字符

mystr.rstrip()

strip

删除mystr字符串两端的空白字符

>>> a = "\n\t hello \t\n"
>>> a.strip()
'hello '

字典

查找元素

a = {'a':1}
print(a.setdefault('b', 2)) # --> 2 # 找不添加到字典中
print(a.get('c'))           # --> None # 找不到不报错
print(a)                    # --> {'a': 1, 'b': 2}

删除元素

a = {'a': 1, 'b': 2}
del a['a'] # 删除指定key
del a      # 删除整个字典在内存里清除
clear a    # 清空字典,a={}

字典常见操作

dict.len()

测量字典中,键值对的个数

dict.keys()

返回一个包含字典所有KEY的列表

dict.values()

返回一个包含字典所有value的列表

dict.items()

返回一个包含所有(键,值)元祖的列表

python内置函数

max() 返回元素

min() 返回最小元素

len(容器)

del(变量) 删除变量

map(function, iterable, ...)

根据提供的函数对指定序列做映射

reduce(function, iterable[, initializer]) # initializer是初始参数

对参数序列中元素进行累积

filter(function, iterable)

用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的迭代器对象(py3)。py2返回列表。

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图