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

目录

  • 内置类型转换
  • 数学
  • 字符串
  • 变量赋值模型(有书上称为便签模型)
  • 简单输入和输出
  • 格式化输入输出
    • 1. 字符串格式化运算符% (类似C中的printf()函数)
    • 2. 字符串格式化方法format()
  • 函数

内置类型转换

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.

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

时间: 2024-08-26 01:39:39

Python入门零散知识整理(! 格式化输出)的相关文章

【python入门到放弃】格式化输出

在python中,格式化输出的四种形式 1.字符串"相加". 使用"+"使得字符串和变量相连. ''' 需求1: 请用户输入自己的姓名,毕业学校,年龄,和爱好,并按照以下的格式进行输出打印: ------------------XXX的自我介绍--------------------- 大家好: 我叫XXX,今年XX岁,我毕业于XXXXX学校,平时喜欢XXXXXXXXXX. ''' name = input("姓名:") school = inp

Python 入门 之 print带颜色输出

Python 入门 之 print带颜色输出 1.print带颜色输出书写格式: 开头部分: \033[显示方式; 前景色 ; 背景色 m 结尾部分: \033[0m 详解: 开头部分的三个参数: 显示方式 字体颜色 背景色 ? 这三个参数是可选参数,可以只写其中的某一个,另外由于表示三个参数不同含义的数值都是唯一的没有重复的,所以三个单数的书写顺序没有固定的要求,但建议按照默认的格式规范书写.对于结尾部分,其实也可以省略,但是为了书写规范,建议\033[开头,\033[0m结尾 字体颜色 背景

Python入门基础知识实例,值得收藏!

7月的编程语言指数榜已经发布,Python 在今年5月首次超越 Java 拿下榜首位置后,仍保持上涨趋势,正逐渐与 Java 拉开差距.(图为与去年 7 月数据对比) 上周为大家简单介绍了如何安装Python和配置环境?相信大家都将Python安装成功了吧~今天小白就为大家分享一些Python的基础知识,希望大家都能快速入门Python~ 1.在Python 语言中,对象是通过引用传递的. 在赋值时,不管这个对象是新创建的,还是一个已经存在的,都是将该对象的引用(并不是值)赋值给变量. 如:x=

python 3 用户输入和格式化输出

# -*- coding:utf-8 -*- #用户输入 && 格式化输出 #getpass 模块是内置的,可以将输入的内容隐藏 import getpass username = input("username:") password = input("password:") age = int (input("age:")) job = input("job:") #print(type(age),type

【Python④】python恼人的字符串,格式化输出

恼人的字符串 计算机只能处理数字,如果要处理文本,就必须先把文本转换为数字才能处理.由于计算机是美国人发明的,因此,最早只有127个字母被编码到计算机里,也就是大小写英文字母.数字和一些符号,这个编码表被称为ASCII编码,比如大写字母A的编码是65,小写字母a的编码是97. 但是要处理中文至少需要两个字节,而且还不能和ASCII编码冲突,所以,中国制定了GB2312编码,用来把中文编进去.全世界有上百种语言,为了扩充ASCII编码,用于显示本国的语言,不同的国家和地区制定了不同的标准,由此产生

Python学习(四)格式化输出

# 格式化输出# % s  d # name = input("please input your name : ")# age = input("please input your age : ")# job = input("please input your job : ")# # msg = '我叫%s , 今年%s' %(name,age)# # print(msg)# # # # # %%  两个%%是为了转义  %  否则直接写57

python 函数基础知识整理

一.函数的定义: 定义:def 关键词开头,空格之后接函数名称和圆括号(),最后还有一个":". def 是固定的,不能变,必须是连续的def三个字母,不能分开... 空格 为了将def关键字和函数名分开 函数名:必须由字母下划线数字组成,不能是关键字,不能是数字开头,函数名还是要有一定的意义能够简单说明函数的功能 括号:是必须加的 注释:每一个函数都应该对功能和参数进行相应的说明,应该写在函数下面第一行.以增强代码的可读性. 调用:就是 函数名() 要记得加上括号 def 函数名(参

python入门基础知识(一)

变量   #1 变量名只能是字母,数字,或者下划线的任意组合 # 2 变量名称的第一个字符不能是数字 # 3 关键词不能声明成变量名 # and,or,for,while,print,break,as,class,if等 在写python的代码时要注意书写规范 #驼峰体  AgeOfJustin=123 #下划线 age_of_justin=123 交互 # input是输入   print是输出 #当用双引号时 双引号中的为字符串,会使你要输入或输出的值更加明确 数字和字符串的简单介绍 #数字

Flask快速入门,知识整理

一.Flask介绍(轻量级的框架,非常快速的就能把程序搭建起来) Flask是一个基于Python开发并且依赖jinja2模板和Werkzeug WSGI服务的一个微型框架,对于Werkzeug本质是Socket服务端,其用于接收http请求并对请求进行预处理,然后触发Flask框架,开发人员基于Flask框架提供的功能对请求进行相应的处理,并返回给用户,如果要返回给用户复杂的内容时,需要借助jinja2模板来实现对模板的处理,即:将模板和数据进行渲染,将渲染后的字符串返回给用户浏览器. “微”