py基础语法简述

py基础,常用sdk

一些要点

  1. python中是没有常量的关键字的,只是我们常常约定使用大写字符组合的变量名表示常量,也有“不要对其进行赋值”的提醒操作
PI = 3.14
  1. python3中有六个标准的数据类型: Number(数字)、String(字符串)、Boolean(布尔)、List(列表)、Tuple(元组)、Sets(集合)、Dictionary(字典)
    不可变数据(4个): Number(数字)、String(字符串)、Tuple(元组)、Boolean(布尔)
    可变数据(3个): List(列表)、Dictionary(字典)、Sets(集合)
    python3支持三种不同的数值类型: 整型(int)、浮点型(float)、复数(complex)

字符串

lstrip、rstrip、strip、replace、find、ljust、rjust、isalpha、isdigit

text = '     abcdef125s  wr2258abcd      '
# 删掉开头和结尾的空格
print('original:', text) 
print('  lstrip:', text.lstrip(' ')) 
print('  rstrip:', text.rstrip(' '))
print('   strip:', text.strip(' '))
print(' replace:', text.replace('a', 'A'))
print(' replace:', text.replace('a', 'A', 1))
print('    find:', text.find('a'))
# 填充字符***
print('text.ljust(50, \'*\') :', text.ljust(50, '*'))
print('text.rjust(50, \'*\') :', text.rjust(50, '*'))
print('text.center(50, \'*\') :', text.center(50, '*'))
# 判断是否全是字母/数字
print('isalpha:', 'abc -', 'abc'.isalpha(), '123 -', '123'.isalpha(), 'a12 -', 'a12'.isalpha())
print('isdigit:', 'abc -', 'abc'.isdigit(), '123 -', '123'.isdigit(), 'a12 -', 'a12'.isdigit())

输出:

original:      abcdef125s  wr2258abcd      
  lstrip: abcdef125s  wr2258abcd      
  rstrip:      abcdef125s  wr2258abcd
   strip: abcdef125s  wr2258abcd
 replace:      Abcdef125s  wr2258Abcd      
 replace:      Abcdef125s  wr2258abcd      
    find: 5
text.ljust(50, '*') :      abcdef125s  wr2258abcd      *****************
text.rjust(50, '*') : *****************     abcdef125s  wr2258abcd      
text.center(50, '*') : ********     abcdef125s  wr2258abcd      *********
isalpha: abc - True 123 - False a12 - False
isdigit: abc - False 123 - True a12 - False

split和join

text2 = 'a,d,dw,d,s,w,t,c,w,'
list1 = text2.split(',')

print('text2:', text2)
print('list1:', list1)
print('join:', ','.join(list1))

输出

text2: a,d,dw,d,s,w,t,c,w,
list1: ['a', 'd', 'dw', 'd', 's', 'w', 't', 'c', 'w', '']
join: a,d,dw,d,s,w,t,c,w,

startswith和endswith

text3 = 'Hello world'
print('start with world:', text3.startswith('world'))
print('start with Hello:', text3.startswith('Hello'))
print('start with world:', text3.endswith('world'))
print('start with Hello:', text3.endswith('Hello'))

输出

start with world: False
start with Hello: True
start with world: True
start with Hello: False

空字符串表示否
空对象会输出None

text4 = ''
print(not text4) # 用于条件时,0、0.0、空字符串被认为是False
print(text4 == '')

sample
print(sample) # 对象为空会定义为None```
输出
True
True
None

list

list按index取值,: 用法,list * 2,list合并

list_1 = [1, 2, 3]
print('list_1 :'.rjust(11), list_1)
list_1.append(4)
print('append(4) :'.rjust(11), list_1)
print('[:1] :'.rjust(11), list_1[1:])
print('[:2] :'.rjust(11), list_1[:2])
print('[-1] :'.rjust(11), list_1[-1])
print('[:] :'.rjust(11), list_1[:])
print()

list_2 = [5, 6, 7]
list_merge = list_1 + list_2
print('list_2 :', list_2)
print('list_2 * 2 :', list_2 * 2)
print('list_1 + list_2 :', list_merge)

输出

   list_1 : [1, 2, 3]
append(4) : [1, 2, 3, 4]
     [:1] : [2, 3, 4]
     [:2] : [1, 2]
     [-1] : 4
      [:] : [1, 2, 3, 4]

list_2 : [5, 6, 7]
list_2 * 2 : [5, 6, 7, 5, 6, 7]
list_1 + list_2 : [1, 2, 3, 4, 5, 6, 7]

list遍历,list按index取值,list插入,list移除,list随机排序,list排序,list判空

import random

my_list = [10, 20, 30]
print('my_list :', my_list)

print('my_list 遍历 :')
for item in my_list:
    print(item)

a, b, c = my_list
print('a, b, c = my_list, a, b, c = ', a, b, c)

print('my_list.index(20) :', my_list.index(20))

my_list.insert(1, 15)
print('my_list.insert(1, 15) :', my_list)

my_list.remove(20)
print('my_list.remove(20) :', my_list)

random.shuffle(my_list)
print('random.shuffle(my_list) :', my_list)

my_list.sort()
print('my_list.sort() :', my_list)

my_list = []
print('my_list = [] :', my_list)

if not my_list:
    print('if not my_list :', 'my_list is empty')
else:
    print('if not my_list :', 'my_list is not empty')

输出

my_list : [10, 20, 30]
my_list 遍历 :
10
20
30
a, b, c = my_list, a, b, c =  10 20 30
my_list.index(20) : 1
my_list.insert(1, 15) : [10, 15, 20, 30]
my_list.remove(20) : [10, 15, 30]
random.shuffle(my_list) : [10, 30, 15]
my_list.sort() : [10, 15, 30]
my_list = [] : []
if not my_list : my_list is empty

list深拷贝

list_deep_copy  = list_2[:]
list_2[1] = 2
print(list_2)
print(list_deep_copy)

输出

[5, 2, 7]
[5, 6, 7]

set

set创建,set遍历,set排序,set插入,discard尝试移除,pop操作,判断set存在,set清空

s0 = set()
s1 = set(list_1)
s2 = set({1, '2'})

print('s0 = set(), s0 :', s0)
print('s1 = set(list_1), s1 :', s1)
print('s2 = set({1, \'2\'}), s2 :', s2, '\n')

print('遍历 s2 :')
for item in s2:
    print(item, type(item))
print('\n')

s2.add(3)
s2.add(4)
s2.add(5)
print('s2.add(3), s2.add(4), s2.add(5), s2 :', s2, '\n')

s2.discard(3)
print('s2.discard(3), s2 :', s2, '\n')

print('len(s2) :', len(s2), '\n')

print('s2.pop() :', s2.pop())
print('s2 :', s2, '\n')

if 4 in s2:
    print('if 4 in s2 :', '4 in s2')
print('\n')

s2.clear()
print('s2.clear(), s2 :', s2, '\n')

输出

s0 = set(), s0 : set()
s1 = set(list_1), s1 : {1, 2, 3, 4}
s2 = set({1, '2'}), s2 : {1, '2'} 

遍历 s2 :
1 <class 'int'>
2 <class 'str'>


s2.add(3), s2.add(4), s2.add(5), s2 : {1, '2', 3, 4, 5} 

s2.discard(3), s2 : {1, '2', 4, 5} 

len(s2) : 4 

s2.pop() : 1
s2 : {'2', 4, 5} 

if 4 in s2 : 4 in s2


s2.clear(), s2 : set() 

tuple

tuple创建,tuple元素计数,tuple查找index

tuple1 = (1, 1, 3, 4, 5)
print(type(tuple1), '\n')

for item in tuple1:
    print(item)
print('\n')

print(tuple1.count(1))
print(tuple1.index(5))

输出

<class 'tuple'> 

1
1
3
4
5


2
4

dict

dict创建,dict取值,dict插入,嵌套dict,打印多层dict,dict设置默认值

my_dict = {'name': '张三', 'age': 18}
print(my_dict)
print(my_dict['name'])
my_dict['city'] = '北京'
print(my_dict)
print('\n')

print('name' in my_dict)
print('sex' in my_dict)
print('age' not in my_dict)
print('\n')

print(my_dict.setdefault('hobby', 'football'))
print(my_dict.setdefault('hobby', 'basketball'))
print('\n')

from pprint import pprint

dict = {'my_dict': my_dict, 'list_merge': list_merge, 's2': s2}
pprint(dict, indent=2)
print('\n')

输出

{'name': '张三', 'age': 18}
张三
{'name': '张三', 'age': 18, 'city': '北京'}


True
False
False


football
football


{ 'list_merge': [1, 2, 3, 4, 5, 6, 7],
  'my_dict': {'age': 18, 'city': '北京', 'hobby': 'football', 'name': '张三'},
  's2': set()}

if、while、for

if判断,while循环,for循环,双层for循环

name = '1'
if name == 'Alice':
    print('Hi, I\'m Alice')
elif name == 'Bob':
    print('Hi, I\'m Bob')
else:
    print('Hi, I\'m', name)
print('\n')

cnt = 3
while cnt > 0:
    print('cnt =', cnt)
    cnt -= 1
print('\n')

for i in range(3):
    print('i =', i)
print('\n')

tmp1 = [1,3,5,7,9]
tmp2 = [2,4,6,8,10]
tmp_list = [tmp1, tmp2]

print(tmp_list)

num_set = set(num for tmp in tmp_list for num in tmp)
print(num_set)

输出

Hi, I'm 1


cnt = 3
cnt = 2
cnt = 1


i = 0
i = 1
i = 2


[[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

exception

def sample(divideBy):
    try:
        return 42/divideBy
    except ZeroDivisionError:
        print('error:invalid arguments')

print(sample(2)) # 输出21.0
print(sample(0)) # 打印错except信息,并输出None

输出

21.0
error:invalid arguments
None

参考:
https://zhuanlan.zhihu.com/p/694203031
https://blog.csdn.net/m0_56051805/article/details/126900242

相关推荐

  1. py基础语法简述

    2024-07-10 00:40:02       20 阅读
  2. c语言基础_指针简述

    2024-07-10 00:40:02       52 阅读
  3. Py-While循环语句

    2024-07-10 00:40:02       47 阅读
  4. Py深度学习基础|关于reshape()函数

    2024-07-10 00:40:02       27 阅读
  5. ES:基础查询语法简单易懂)

    2024-07-10 00:40:02       37 阅读
  6. rust给py写拓展如此简单

    2024-07-10 00:40:02       54 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-10 00:40:02       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-10 00:40:02       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-10 00:40:02       57 阅读
  4. Python语言-面向对象

    2024-07-10 00:40:02       68 阅读

热门阅读

  1. 代码随想录算法训练营:20/60

    2024-07-10 00:40:02       21 阅读
  2. 【6-1:全链路压测】

    2024-07-10 00:40:02       23 阅读
  3. 识别色带后执行相应命令

    2024-07-10 00:40:02       24 阅读
  4. QMdiAreaQMdiAreaQMdiAreaQMdiArea

    2024-07-10 00:40:02       22 阅读
  5. Jacoco的覆盖率原理

    2024-07-10 00:40:02       21 阅读
  6. 中英双语介绍美国的州:阿肯色州(Arkansas)

    2024-07-10 00:40:02       28 阅读
  7. Socket网络通信流程

    2024-07-10 00:40:02       27 阅读
  8. 《妃梦千年》第二十九章:朝中波澜

    2024-07-10 00:40:02       22 阅读
  9. FineReport报表开发步骤

    2024-07-10 00:40:02       28 阅读
  10. py每日spider案例之magnet篇

    2024-07-10 00:40:02       19 阅读
  11. Gridea + SFTP +Docker + Nginx 配置博客-CSDN

    2024-07-10 00:40:02       24 阅读