【python复习随记】

【python复习随记】

缩进要对

image

多行语句:使用反斜杠\

total = item_one + \
        item_two + \
        item_three

在 [], {}, 或 () 中的多行语句,不需要使用反斜杠 \

total = ['item_one', 'item_two', 'item_three',
        'item_four', 'item_five']

复数complex

a+bj : a实部 b虚部 j虚数单位

字符串

(1)多行字符串:三引号(''' 或 """)
(2)转义符 \
使用r可以让反斜杠不发生转义: r"this is a line with \n" 则\n 会显示
(3)用+运算符连接在一起,用*运算符重复
(4)两种索引方式:从左往右以0开始,从右往左以-1开始
(5)切片 str[start:end:step]
step:步长 : 如果step==-1:逆向
image

print(str[0:-1])    # 输出第一个到倒数第二个(注意!)的所有字符
"""
->str[-1]:倒数第一个字符
"""
print(str[2:])      # 输出从第三个开始后的所有字符(注意!)

(6)字符串不可直接被修改:需要先转换为List再还原成String
eg 翻转字符串(不翻转字符)
def reverseWords(input):

def reverseWords(input): 
      
    # 通过空格将字符串分隔符,把各个单词分隔为列表
    inputWords = input.split(" ") 
  
    # 翻转字符串
    # 假设列表 list = [1,2,3,4],  
    # list[0]=1, list[1]=2 ,而 -1 表示最后一个元素 list[-1]=4 ( 与 list[3]=4 一样) 
    # inputWords[-1::-1] 有三个参数
    # 第一个参数 -1 表示最后一个元素
    # 第二个参数为空,表示移动到列表末尾
    # 第三个参数为步长,-1 表示逆向
    inputWords=inputWords[-1::-1] 
  
    # 重新组合字符串
    output = ' '.join(inputWords) 
      
    return output 
  
if __name__ == "__main__": 
    input = 'I like runoob'
    rw = reverseWords(input) 
    print(rw)

同一行显示多条语句:使用分号;分割

print默认输出换行

※要实现不换行需要在变量末尾加上 end=""

导入模块

整个导入 import
从模块导入函数

from somemodule import somefunction  # 导入一个函数
from somemodule import firstfunc, secondfunc, thirdfunc  # 导入多个函数
from somemodule import *   # 导入全部函数

多变量赋值

a, b, c = 1, 2, "runoob"

查询变量类型

type()

a, b, c, d = 20, 5.5, True, 4+3j
print(type(a), type(b), type(c), type(d))
>>> <class 'int'> <class 'float'> <class 'bool'> <class 'complex'>

isinstance()

a = 111
print(isinstance(a, int))
>>> True

image

布尔型:一种int

True1、False0 会返回 True,但可以通过 is 来判断类型
image
image

删除 del

image
->会报错:var2被删掉了

数值运算

/ :取小数
// :整除
image
image

列表索引

image
※注意:末尾取不到!

元组tuple

创建只有一个元素的元组,需要注意在元素后面添加一个逗号

tup1 = ()    # 空元组
tup2 = (20,) # 一个元素,需要在元素后添加逗号

集合set:去重复元素

(1)创建集合 set(){}
(2)可进行运算
image

字典dictionary

posted @ 2025-01-02 20:43  White_ink  阅读(33)  评论(0)    收藏  举报