学习序列前预习知识

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33656602/article/details/82827171

内建函数

split

将字符串按照指定的符号进行分割,返回一个列表

_str='a_b_c'
_str.split('_')
['a', 'b', 'c']

join

将列表按指定的符号进行合并,返回一个字符串

_str
'a_b_c'
_list=_str.split('_')
_list
['a', 'b', 'c']
'_'.join(_list)
'a_b_c'

len

求对象(序列)的长度

  • 列表
    _list = [1, 2, 3, 4]
    len(_list)
    
  • 元组
    _tuple=(1, 2, 3, 4)
    len(_tuple)
    4
    
  • 字典
    _dict={1:2, 3:4}
    len(_dict)
    2
    

int

将对象转成 int 型数据

  • 将字符串型数字转换成整型
    var = int('123')
    var
    123
    isinstance(var, int)
    True
    
  • 将字符串型字符转换成整型
    var = int('a')
    Traceback (most recent call last):
      Python Shell, prompt 26, line 1
    builtins.ValueError: invalid literal for int() with base 10: 'a'
    

str

将对象转成 str 型数据

_int = 123
_str = str(_int)
_str
'123'
isinstance(_str, str)
True

id

求出对象的内存地址,常用于通过查看变量、对象的内存地址来判断变量、对象是否有变化

a = 5
id(a)
1905880672
b = a
id(b)
1905880672

sum

对整数序列求和

  • 列表
_list = [1, 2, 3, 4]
sum(_list)
10
  • 元组
_tuple=(1, 2, 3, 4)
sum(_tuple)
10

max

求序列中最大值

  • 列表

    _list=[1, 2, 3, 4]
    max(_list)
    
  • 元组

    _tuple=(1, 2, 3, 4)
    max(_tuple)
    4
    
  • 字典

    _dict={1:2, 3:4}
    max(_dict)
    3
    
  • 不支持求整数和字符串元素之间的最大值

    _list=[1, 2, 3, 'a', 'b']
    max(_list)
    Traceback (most recent call last):
      Python Shell, prompt 19, line 1
    builtins.TypeError: '>' not supported between instances of 'str' and 'int'
    

异常初识

try: ... except: ...

print(car)
Traceback (most recent call last):
  Python Shell, prompt 48, line 1
builtins.NameError: name 'car' is not defined
try:
    print(car)
except:
    print('print car cause wrong')
print car cause wrong

打印时的注释部分

%s 方式

  • 打印日志时:想输出一个变量内容怎么办?
    输出日志的地方:%s,在日志外部 %var

    #coding:gbk
    car = 'benz'
    print('I have a %s car' %car)
    
    I have a benz car
    

format 方式

基本语法是通过 {} 和 : 来代替以前的 % 。
format 函数可以接受不限个参数,位置可以不按顺序。

  • 不设置指定位置,按默认顺序
    '{} {}'.format("Hello", "World!")
    'Hello World!'
    
  • 设置指定位置
    '{1} {0}'.format("Hello", "World!")
    'World! Hello'
    
    print("姓:{first_name}, 名:{last_name}".format(first_name='su', last_name='ym' ))
    姓:su, 名:ym
    
    

open 语法的 read 和 readlines 初识

open() : 在python 中打开一个文件

  • 参数
  1. 文件路径
  2. 打开方式,默认’r’

open.txt 文件内容

a
b
c
d

read

把文件中的内容读取出来,以字符串的格式存储

#coding:utf-8
f = open(r'C:\Users\admin\Desktop\open.txt')
content = f.read()
print(content)
f.close()

运行脚本结果

a
b
c
d

readlines

把文件中每一行作为一项放到一个列表中,返回一个 list

#coding:utf-8

f = open(r'C:\Users\admin\Desktop\open.txt')
content = f.readlines()
print(content)

f.close()

运行脚本结果

['a\n', 'b\n', 'c\n', 'd']

注意事项

open 一个文件一定要将之关闭,否则可能耗尽服务器的文件描述符的数量,从而导致服务器宕机。

file.close()

退出 python 进程如何退出呢?

exit()或者quit()

猜你喜欢

转载自blog.csdn.net/qq_33656602/article/details/82827171