码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2020-01-28 19:11:59      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:res   which   mem   格式   指针   hex   对齐   read   insert   

内置类型转换

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

技术图片

补充:

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

数学

  • 分数
    python 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的值都没变,但内存中列表的值发生了改变。

简单输入和输出

  • 从命令行获取输入: input和raw_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) :
    | Conversion | Meaning | Notes |
    | --- | --- | --- |
    | ‘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
    python 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...

  2. 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
    python 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?
  • 添加键、属性和偏移量
    python 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
        • The available integer presentation types
          | 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‘ |
        • The available floating point presentation types are:
          | 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.|

函数

  • 基本格式
    python def func_name(para1, para2,...): code
  • 默认值, 有默认值的参数要在普通参数后面
    python def func_name(para1, para2 = ‘‘,...): code
  • 返回值, 可以是元组
    python def func_name(para1, para2,...): code return para1 + para2, para1 - para2
  • 控制执行
    ```python
    def main():
    pass

    if name == "main": # 只有调用该程序时__name__的值才为"main"
    main()
    ```
  • 传递数量可变的参数
    1. *args(也是可以用其他名字)将函数调用表达式中的多余参数
    2. **kwargs(可以用其他名称)将函数调用表达式中给未知参数"赋值"的表达式用字典储存
    • 示例代码:
      ```python
      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前。

  • 改变实参(利用列表)
    • 示例代码:
      ```python
      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.

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

标签:res   which   mem   格式   指针   hex   对齐   read   insert   

原文地址:https://www.cnblogs.com/alohana/p/12238501.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!