python入门笔记(1)

Python 提供的全部内置函数

>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

字符

在这里插入图片描述
原始字符串:

>>> 未使用原始字符串
>>> print("D:\three\two\one\now")
D:        hree        wo\one
ow
>>> # 使用原始字符串
>>> print(r"D:\three\two\one\now")
D:\three\two\one\now

三引号:引用多行文本

>>> poetry = """
面朝大海,春暖花开
从明天起,做一个幸福的人
喂马、劈柴,周游世界
从明天起,关心粮食和蔬菜
我有一所房子,面朝大海,春暖花开
"""

数字 + 运算

随机数函数

在这里插入图片描述

精确计算小数(浮点数)

在这里插入图片描述

复数

>>> x = 1 + 2j
>>> x.real
1.0
>>> x.imag
2.0

数字运算

在这里插入图片描述
x // y(地板除):取比目标结果小的最大整数。

abs(x)(取绝对值):如果传入一个复数,abs() 函数返回复数的模。

int float complex 均为转换数值格式的函数。

pow() 和 ** 的区别:pow()函数支持第 3 个参数。如果传入第 3 个参数,则将幂运算的结果和第 3 个参数进行取余数运算。

布尔类型

使用 bool() 函数可以直接给出 True 或者 False 的结果。

结果是 True 的情况非常多,但 False 却是屈指可数,下面这些几乎就是结果为 False 的所有情况:

  • 定义为 False 的对象:None 和 False
  • 值为 0 的数字类型:0, 0.0, 0j, Decimal(0), Fraction(0, 1)
  • 空的序列和集合:‘’, (), [], {}, set(), range(0)

and or not
在这里插入图片描述

字符串

Python将列表、元组和字符串统称为序列。
在这里插入图片描述

切片

a = "1234567"
a[:1:-1]
          
'76543'

(前半部分下标定位,结尾“:-1”反转)

FUNCTION

字母大小写

>>> x = "i love FishC"
>>> x.capitalize()
'I love fishc'
>>> x.casefold()
'i love fishc'
>>> x.title()
'I Love Fishc'
>>> x.swapcase()
'I LOVE fISHc'
>>> x.upper()
'I LOVE FISHC'
>>> x.lower()
'i love fishc'

格式左中右

>>> x = "有内鬼,停止交易!"
>>> x.center(15)
'   有内鬼,停止交易!   '
>>> x.ljust(15)
'有内鬼,停止交易!      '
>>> x.rjust(15)
'      有内鬼,停止交易!'
>>> x.zfill(15)
'000000有内鬼,停止交易!'
>>> "520".zfill(5)
'00520'
>>> "-520".zfill(5)
'-0520'
>>> x.center(15, "淦")
'淦淦淦有内鬼,停止交易!淦淦淦'
>>> x.ljust(15, "淦")
'有内鬼,停止交易!淦淦淦淦淦淦'
>>> x.rjust(15, "淦")
'淦淦淦淦淦淦有内鬼,停止交易!'

查找

>>> x = "上海自来水来自海上"
>>> x.count("海")
2
>>> x.count("海", 0, 5)
1
>>> x.find("海")
1
>>> x.rfind("海")
7
>>> x.find("龟")
-1

替换(可用于删除?)

replace(old, new, count=-1) 返回一个将所有 old 参数指定子字符串替换为 new 的新字符串。另有一个 count 参数是指定替换的次数,默认值 -1 表示替换全部。

>>> "在吗!我在你家楼下,快点下来!!".replace("在吗", "想你")
'想你!我在你家楼下,快点下来!!'

translate(table)根据 str.maketrans(x[, y[, z]]) 设定的转换规则返回一个新字符串。

>>> table = str.maketrans("ABCDEFG", "1234567")
>>> "I love FishC.com".translate(table)
'I love 6ish3.com'

str.maketrans() 方法还支持第三个参数,表示将指定字符串忽略:

>>> "I love FishC.com".translate(str.maketrans("ABCDEFG", "1234567", "love"))
'I  6ish3.cm'

判断

Function用途
startswith(a, start, end)判断a是否出现在字符串的[start, end]子字符串的起始位置
endswith(a, start, end)判断a是否出现在字符串的[start, end]子字符串的结束位置
istitle()判断字符串中所有单词是否都以大写字母开头,其余字母均为小写
isupper()判断字符串中所有字母是否都是大写
islower()判断字符串中所有字母是否都是小写
isalpha()判断字符串是否只由字母组成
isascii()判断字符串是否只由 ASCII 字符组成
isspace()判断是否为空白字符串
isprintable()判断字符串中是否所有字符都可打印
isdecimal() 和 isdecimal()判断是否十进制数字
isnumeric()可判断内容包括十进制数字、罗马数字、中文数字等
isalnum()isalpha()、isdecimal()、isdigit() 或 isnumeric() 任一返回 True便为 True
isidentifier()判断字符串是否一个合法的 Python 标识符(做变量名所必须)

startswith() 和 endswith() 的其他用法:

>>> x = "她爱Pyhon"
>>> if x.startswith(("你", "我", "她")):
...     print("总有人喜爱Pyhon")
...
总有人喜爱Pyhon

isidentifier():

>>> "I a good gay".isidentifier()
False
>>> "I_a_good_gay".isidentifier()
True
>>> "FishC520".isidentifier()
True
>>> "520FishC".isidentifier()
False

如果想判断一个字符串是否为 Python 的保留标识符(如 “if”、“for”、“while” ),可以使用 keyword 模块的 iskeyword() 函数来实现:

>>> import keyword
>>> keyword.iskeyword("if")
True
>>> keyword.iskeyword("py")
False

截取/删除

去除空白(括号内为None):

>>> "    左侧不要留白".lstrip()
'左侧不要留白'
>>> "右侧不要留白    ".rstrip()
'右侧不要留白'
>>> "    左右不要留白    ".strip()
'左右不要留白'

删除指定字符串:

>>> "www.ilovefishc.com".lstrip("wcom.")
'ilovefishc.com'
>>> "www.ilovefishc.com".rstrip("wcom.")
'www.ilovefish'
>>> "www.ilovefishc.com".strip("wcom.")
'ilovefish'

删除指定的一个字符串(只能在首或尾)

>>> "www.ilovefishc.com".removeprefix("www.")
'ilovefishc.com'
>>> "www.ilovefishc.com".removesuffix(".com")
'www.ilovefishc'

拆分

partition() 只能拆分成两段:

a = 'aaa.bbb.ccc.ddd'
a.partition('.')
('aaa', '.', 'bbb.ccc.ddd')
a.rpartition('.')
('aaa.bbb.ccc', '.', 'ddd')

split() 拆分成多段:

>>> "苟日新,日日新,又日新".split(",")
['苟日新', '日日新', '又日新']
>>> "苟日新,日日新,又日新".rsplit(",")
['苟日新', '日日新', '又日新']
>>> "苟日新,日日新,又日新".split(",", 1)
['苟日新', '日日新,又日新']
>>> "苟日新,日日新,又日新".rsplit(",", 1)
['苟日新,日日新', '又日新']

splitlines() 按行拆分:

>>> "苟日新\n日日新\n又日新".splitlines()
['苟日新', '日日新', '又日新']
>>> "苟日新\r日日新\r又日新".splitlines()
['苟日新', '日日新', '又日新']
>>> "苟日新\r日日新\r\n又日新".splitlines(True)
['苟日新\r', '日日新\r\n', '又日新']

拼接

可使用 “+” 但面对大批量数据时 join() 的拼接速度更快。

>>> ".".join(["www", "ilovefishc", "com"])
'www.ilovefishc.com'

字符串拼接速度大比拼

字符串格式化

方法示例
直接用{ }"1+2={}, 2的平方是{},3的立方是{}".format(1+2, 2*2, 3*3*3)
位置索引"{0}{0}{1}{1}".format("是", "非")
关键字索引"我叫{name},我爱{fav}。".format(name="小甲鱼", fav="Pyhon")
同时使用位置和关键字索引"我叫{name},我爱{0}。喜爱{0}的人,运气都不会太差^o^".format("python", name="小甲鱼")

字符串格式化语法

format_spec     ::=  [fill][align][sign][0][width][grouping_option][.precision][type][#]
fill            ::=  <any character>
align           ::=  "<" | ">" | "=" | "^"
sign            ::=  "+" | "-" | " "
width           ::=  digit+
grouping_option ::=  "_" | ","
precision       ::=  digit+
type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

对齐选项([align])

在这里插入图片描述
示例:

>>> "{:^}".format(250)
'250'
>>> "{:^10}".format(250)
'   250    '
>>> '{2:>10}{1:^}{0:<10}'.format(2,3,4) #下标定位
'         432         '
>>> '{2:>10}{1}{0:<10}'.format(2,3,4)
'         432         '
>>> "{left:>10}{right:<10}".format(right=520, left=250) #关键字定位
'       250520       '

填充选项([fill])

在指定宽度前添加一个 ‘0’,则表示为数字类型启用感知正负号的 ‘0’ 填充效果(只对数字有效):

>>> "{:010}".format(520)
'0000000520'
>>> "{:030}".format(520)
'000000000000000000000000000520'
>>> "{:110}".format(520) #话说这是加了个什么
'                                                                                                           520'
>>> "{:010}".format(-520)
'-000000520'

还可以在[align]前面通过[fill]指定填充的字符:

>>> "{1:%>10}{0:%<10}".format(520, 250)
'%%%%%%%250520%%%%%%%'
>>> "{:0=10}".format(520)
'0000000520'
>>> "{:0=10}".format(-520)
'-000000520'

符号([sign])选项

仅对数字类型有效,可使用下面3个值:
在这里插入图片描述

'{:+}'.format(5)
'+5'
'{:-}'.format(5, -2)
'5'
'{:+} {:-}'.format(5, -2)
'+5 -2'

千分位分隔符

'{:,}'.format(134567)
'134,567'

精度([.precision])选项

对于以 ‘f’ 或 ‘F’ 格式化的浮点数值来说,是限定小数点显示多少个数位;
对于以 ‘g’ 或 ‘G’ 格式化的浮点数值来说,是限定小数点前后共显示多少个数位;
对于非数字类型来说,限定最大字段的大小,即要使用多少个来自字段内容的字符;
对于整数来说,不允许使用该选项值。

'{:2f}'.format(3.1415926)
'3.141593'
'{:.2f}'.format(3.1415926)
'3.14'
'{:2g}'.format(3.1415926)
'3.14159'
'{:.2g}'.format(3.1415926)
'3.1'
'{:2}'.format('afghjk')
'afghjk'
'{:.2}'.format('afghjk')
'af'

类型([type])选项

决定数据的呈现方式。

整数
在这里插入图片描述

浮点数、复数和整数(自动转换为等值的浮点数)
在这里插入图片描述
示例:

print "My name is %s and weight is %d kg!" % ('Zara', 21) 
My name is Zara and weight is 21 kg!

扩展延伸

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值