Python入门零散知识整理(! 格式化输出)

Python入门零散知识整理(格式化输出)

本文图片来源菜鸟教程

内置类型转换


type()可直接查看变量类型。

补充:

>>>dict(name = 'aloha', food = 'apple pie', id = '0')
{'name': 'aloha', 'food': 'apple pie', 'id': '0'}

数学

  • 分数
from fractions import Fraction
fractions.Fraction(a,b)    # a为分子,b为分母
  • 复数
    1. complex(real,imag)
    2. j为虚数单位,如2+3j

字符串

  • “成员函数”
    • upper(): 返回全部转换为大写的原字符串。
    • lower(): 返回全部转换为小写的原字符串。
    • capitalize(): 返回句首字母大写的原字符串。
    • title(): 返回每个单词的首字母大写的原字符串。
    • is_alpha(): 检查是否全为字母。
    • is_digit(): 检查是否全为数字。
  • 删除多余空格(或其他字符)
    • strip()
      1. 无参数: 去除首尾的所有空格或换行符。
      2. 给予单个字符作为参数: 若字符串首/尾为此字符, 去除之。
    • lstrip(): 同strip()不过只作用于字符串左部。
    • rstrip(): 同strip()不过只作用于字符串右部。
  • 查找和替换文本
    • count(): 计算子字符串出现次数。
    • find(): 查找子字符串第一次出现的位置。如果没找到,则返回-1。
    • replace(str1, str2): 将所有子字符串str1用str2代替。

变量赋值模型(有书上称为便签模型)

python中赋值是创建一个引用的过程(在Python中,从变量到对象的连接称作引用)。变量实际上是指向对象的一个指针。可以用变量指向(也许是引用)任何类型的数据。

根据右值可将赋值分为两种

  1. 右值为具体的值:
    用该值在内存中创建一个对象,并使该变量引用此对象。
    注意:数字和字符串在Python中其实均不可改变。
  2. 右值为变量:
    共享同一个对象。

注:引用可以通过del删除。



Python中的列表可以起到类似指针的效果。

a = [1, 2, 3]
b = a
a[0] = '1'
print(b)
['1', 2, 3]

在修改a[0]后,b[0]也被修改了。
a[0] = '1'修改的是内存中列表的第一个元素。ab的值都没变,但内存中列表的值发生了改变。

简单输入和输出

从命令行获取输入: inputraw_input函数。Python3.7中将自动识别类型的print和将输入处理为纯字符串的raw_print合并为print,功能相当于原来的raw_print。具体内容见以下摘录的原文:

PEP 3111: raw_input() was renamed to input(). That is, the new input() function reads a line from sys.stdin and returns it with the trailing newline stripped. It raises EOFError if the input is terminated prematurely. To get the old behavior of input(), use eval(input()).

输出到命令行:

print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream.

  • value: 要输出的值, 可以是字符串、数字、列表、字典、元组等, 可同时给出多个值。
  • sep: 分隔每个值的字符串, 默认为空格。
  • end: 附加在最后一个值后的字符串, 默认为换行符。
  • file: 一个文件对象或流对象, 如open()创建的对象, 默认为标准输出, 即输出到控制台。另外,还可以设置为sys.stdin,sys.stderr。
  • flush: 是否强制输出并清空流。

格式化输入输出

1. 字符串格式化运算符% (类似C中的printf()函数)

  1. 在%操作符的左侧放置一个需要进行格式化的字符串,这个字符串带有一个或多个嵌入的转换目标,都以%开头(例如,%d)。
  2. 在%操作符右侧放置一个(或多个,嵌入到元组中)对象,这些对象将会插入到左侧想让Python进行格式化字符串的一个(或多个)转换目标的位置上去。

标准格式:

%[(name)][flags][minimumwidth][.precision]typecode
  1. 字符串格式化代码 (typecode, 以下称conversion) :
ConversionMeaningNotes
'd'Signed integer decimal.
'i'Signed integer decimal.
'o'Signed octal value.(1)
'u'Obsolete type – it is identical to 'd'.(6)
'x'Signed hexadecimal (lowercase).(2)
'X'Signed hexadecimal (uppercase).(2)
'e'Floating point exponential format (lowercase).(3)
'E'Floating point exponential format (uppercase).(3)
'f'Floating point decimal format.(3)
'F'Floating point decimal format.(3)
'g'Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.(4)
'G'Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.(4)
'c'Single character (accepts integer or single character string).
'r'String (converts any Python object using repr()).(5)
's'String (converts any Python object using str()).(5)
'a'String (converts any Python object using ascii()).(5)
'%'No argument is converted, results in a '%' character in the result.

Notes:

  1. The alternate form causes a leading octal specifier ('0o') to be inserted before the first digit.
  2. The alternate form causes a leading '0x' or '0X' (depending on whether the 'x' or 'X' format was used) to be inserted before the first digit.
  3. The alternate form causes the result to always contain a decimal point, even if no digits follow it.
    The precision determines the number of digits after the decimal point and defaults to 6.
  4. The alternate form causes the result to always contain a decimal point, and trailing zeroes are not removed as they would otherwise be.
    The precision determines the number of significant digits before and after the decimal point and defaults to 6.
  5. If precision is N, the output is truncated to N characters.
  6. See PEP 237.
  1. flags
i = 4.53459
print(r'%-10.5f: ', '...%-10.5f...'%(i))    # - 左对齐
print(r'%+10.5f: ', '...%+10.5f...'%(i))    # + 显示符号
print(r'%010.5f: ', '...%010.5f...'%(i))    # 0 空位补零
%-10.5f:  ...4.53459   ...
%+10.5f:  ...  +4.53459...
%010.5f:  ...0004.53459...
  1. minimumwidth和precision
    • minimumwidth指定至少的数字长度(包括小数点、符号),precision指定数字精度(即小数点后位数) 。
    • 可以用*表明两者的值从%运算符后获取。
    • 精度默认为0。
    • 直接用%f,则默认保留6位小数点后数字。
i = 4.53459
print(r'%-5.2f : ', '...%-5.2f...'%(i))
print(r'%-f    : ', '...%-f...'%(i))
print(r'%-.f   : ', '...%-.f...'%(i))
print(r'%-0.0f : ', '...%-0.0f...'%(i))

width = 5
print(r'%-*.*f : ', '...%-*.*f...'%(width, width-2, i))
%-5.2f :  ...4.53 ...
%-5.10f:  ...4.5345900000...
%-f    :  ...4.534590...
%-.f   :  ...5...
%-0.0f :  ...5...
%-*.*f :  ...4.535...
  1. name

用在基于字典的字符串格式化中,如:

>>>"%(name)s-%(id)d loves %(food)s"%{**dict(name = 'aloha', food = 'apple pie', id = 0)}
'aloha-0 loves apple pie'

常搭配vars()(返回保存了一个所有的变量名:数据值对的字典)使用:

>>>name, food = "John", "apple pie"
>>>print("I'm %(name)s. My favorite food is %(food)s"%vars())
I'm John. My favorite food is apple pie

2. 字符串格式化方法format()

可以通过位置或关键字指定, 底层实现使用了*args**kwargs

template = "{0} {name}. {greeting}\n";    # {0}和{}等效
me = template.format("My name is", name = "aloha", greeting = "What's your name?")
he = template.format("I'm", name = "Stephen Prata", greeting ="How do you do?")
print(me, he, sep = '')
My name is aloha. What's your name?
I'm Stephen. How do you do?

添加键、属性和偏移量:

template = "{} {name[0]}. {greeting}\n";    # {0}和{}等效
print(template.format("I'm", name = "Stephen Prata".split(), greeting = "How do you do?"))
I'm Stephen. How do you do?

限制:

  • 不能调用成员函数。
  • 只有单个的正的偏移(索引)才能在格式化字符串的语法中有效, 切片或负索引无效。
添加具体格式化

格式:

{[fieldname] [!conversionflag] [:formatspec]}
  • fieldname: 指定参数的一个数字或关键字,后面跟着可选的.<mem_name>[<index>]成分引用。
  • conversionflag: 相当于对原输出字符串进行以下相应函数的调用。
    • s: str(obj, /): 调用obj.__str__(). 如果obj没有定义__str__()函数, 则转为调用repr()函数。
    • r: repr(obj, /): 尝试生成(yield)一个字符串, 使eval(repr(obj)) == obj, 否则显示类。似'<function main at 0x000001B1CCD5FA68>'的obj的详细信息. 可以通过定义__repr__()函数控制repr()函数的输出。
    • a: ascii(obj, /): 类似repr(), 但是会用转义格式表示非ASCII字符。
  • formatspec
    {[[fill] align] [sign] [#] [0] [minimumwidth] [.precision] [typecode]}
    
    • fill: 指定用来填充空位的字符, 没有指定minimumwidth或minimumwidth不大于所需长度的话,指定fill没有意义。
    • align: 指定对齐方式。
      '<'(默认)、'^''>'分别为左、中、右对齐, '='(仅限于数字)强行用填充字符填在符号(如果有)和数字之间。
    • sign: 只对数字有效, 指定符号显示方式。
      • '+': 正负数都显示符号。
      • '-': 负数显示符号。
      • ' ': 正数前置空格, 负数显示符号。
    • '#': 给出'#'表示会自动为输出的二进制(0b***)、八进制(0o***)、十六进制(0x***)数字加上前缀。
    • '0': 等价于指定fill为'0'、align为'='
    • minimumwidth和precision同%运算符。
    • typecode: 如下:

下面两张表分别是整数类型和浮点数类型的typecode:

typecode
'b'Binary. Outputs the number in base 2.
'c'Character. Converts the integer to the corresponding Unicode character before printing.
'd'Decimal Integer. Outputs the number in base 10.
'o'Octal format. Outputs the number in base 8.
'x'Hex format. Outputs the number in base 16, using lower-case letters for the digits above 9.
'X'Hex format. Outputs the number in base 16, using upper-case letters for the digits above 9.
'n'Number. This is the same as ‘d’, except that it uses the current locale setting to insert the appropriate number separator characters.
'' (None)the same as ‘d’
typecode
'e'Exponent notation. Prints the number in scientific notation using the letter ‘e’ to indicate the exponent.
'E'Exponent notation. Same as ‘e’ except it converts the number to uppercase.
'f'Fixed point. Displays the number as a fixed-point number.
'F'Fixed point. Same as ‘f’ except it converts the number to uppercase.
'g'General format. This prints the number as a fixed-point number, unless the number is too large, in which case it switches to ‘e’ exponent notation.
'G'General format. Same as ‘g’ except switches to ‘E’ if the number gets to large.
'n'Number. This is the same as ‘g’, except that it uses the current locale setting to insert the appropriate number separator characters.
'%'Percentage. Multiplies the number by 100 and displays in fixed (‘f’) format, followed by a percent sign.
''(None)similar to ‘g’, except that it prints at least one digit after the decimal point.

函数

基本使用

基本格式:

def func_name(para1, para2,...):
    code

默认值, 有默认值的参数要在普通参数后面:

def func_name(para1, para2 = '',...):
    code

返回值, 可以是元组:

def func_name(para1, para2,...):
    code
    return para1 + para2, para1 - para2

高级使用

控制执行
def main():
    pass

if __name__ == "__main__":    # 只有调用该程序时__name__的值才为"__main__"
    main()
传递数量可变的参数
  1. *args(也是可以用其他名字)将函数调用表达式中的多余参数存储为列表。
  2. **kwargs(可以用其他名称)将函数调用表达式中给未知参数"赋值"的表达式用字典储存。
def main(food, name, *args, **kwargs):
    print("%s love(s) %s." % (name, food))
    print(args)
    print(kwargs)

main("apple pie", "aloha", "I'm", "telling", "nothing.", age = 100, id = 0)
aloha love(s) apple pie.
("I'm", 'telling', 'nothing.')
{'age': 100, 'id': 0}

注意:在函数声明中,普通参数(regular parameter)必须在这两种参数前,*parameter必须在**parameter前。

改变实参(利用列表)

示例代码:

    def getname(arr):
        arr[0] = str(input("What's your name?\n"))

    names = ["username", "aloha"]
    getname(names)
    print("Hello %s, I'm %s."%(names[0], names[1]))

输出:

What's your name?
Stephen
Hello Stephen, I'm aloha.

迭代,iter和next

  • python中的基础类型没有next()方法。
  • 在隐式迭代时会自动使用内置的iter()方法将裸类型转化为迭代器。
  • 从技术上讲,隐式迭代调用I.__next__()方法而不是next(I)函数,两者几乎等效,但后者实现时调用前者(这并不是Python的语言特征)。
>>> l = [1, 2, 3]
>>> l
[1, 2, 3]
>>> i = iter(l)
>>> i
<list_iterator object at 0x0000026D8AB19708>
>>> i.__next__()
1
>>> i.__next__()
2
>>> for i in l:
	print(i, end = ' ')

	
1 2 3 
>>> l.__next__()
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    l.__next__()
AttributeError: 'list' object has no attribute '__next__'
>>> 
  • 在最近的Python中,字典也有一个迭代器,返回值为一个键值,标准的字典遍历方法如下:
>>>for key in D:
       print(key, D[key])

    
name aloha
ID 2019341105
>>> 

列表解析

>>> L = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> L = [i*2 for i in L]
>>> L
[2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> 
  • 标准格式:[<exp> for <var> in <Iteratable object>]
    • 表达式<exp>为循环变量,不一定需要包含<var>
    • 后面的类似for循环头部的部分声明了循环变量<var>以及一个可迭代对象<Iteratable object>
  • 列表解析可用for循环等方式代替,但列表解析在内部是以C语言实现的,运行速度通常快一倍。

在文件中使用列表解析

  1. 基础用法示例:去除换行符:
>>>f = open('myfile.txt')
>>>lines = [line.rstrip() for line in f.readlinse()]
>>>for line in lines:
    print(line, end = '\n')
  1. if子句
lines = [line.rstrip() for line in f.readlinse() if line[0] != 'p']
  1. 嵌套
>>>[pre + lat for pre in 'abc' for lat in 'xyz']
['ax', 'ay', 'az', 'bx', 'by', 'bz', 'cx', 'cy', 'cz']
  1. map()函数
    返回一个map对象类似于列表解析,但第一个函数必须是一个函数名而不能是任意表达式。
>>> f = open('myfile.txt')
>>> map(str.upper, f)
<map object at 0x00000208E2FA9748>
>>> list(map(str.upper, f))
['HELLOW\n', 'WORLD\n', "I'M\n", 'ALOHA\n', 'LIU']
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值