python学习笔记、常用方法str、list、dict、md5、zip、索引遍历【笔记】

字符串操作相关

  • 字符串是否包含指定子串
	# 方法一:
	str = "今日出去游玩"
	# 包含返回True,否则false
    bool = "今日" in str:
    # 方法二:
   str1 = "abcdef,acdsdc"
   str2 = "addc"
   index = str1.find(str2)
   print("包含的话,返回第一次出现的位置,没有的话为负1", index)
  • 字符串截取子串
   str = "abcdef,acdsdc"
   str[1:3]  # bc
  • 字符串查找指定字符索引
     	    # 查找网页内容中body标签的索引开始位置
			start = content.index('<body>')
            ent = content.index('</body>')
  • 去掉前后空格
		context = context.strip()

集合操作相关

  • 集合添加元素
    – 四种方式:append(),extend(),insert(), +加号
  1. append()
	list = ["a","b"]
	list.append("c") # ['a', 'b', 'c']
	# 如果是一个list,那么这个list将作为一个整体进行追加
	list.append(["1","2"]) # ['a', 'b', ['1', '2']]
  1. extend()
	list = ["a", "b"]
	# 注意和append()的区别
    list.extend(["1", "2"]) # ['a', 'b', '1', '2']
    print(list)
  1. insert()
    insert() 将一个元素插入到列表中,但其参数有两个(如insert(1,"g")),第一个参数是索引点,即插入的位置,第二个参数是插入的元素
    list = ["a", "b"]
    list.insert(1, ["1", "2"])
    print(list) # ['a', ['1', '2'], 'b']
  1. +
    将两个list相加,会返回到一个新的list对象
    list = ["a", "b"]
    list2 = ["10", "20"]
    new_list = list + list2
    print(new_list) #['a', 'b', '10', '20']
  • 遍历集合---提供索引
    – 普通遍历
    list1 = [True, 2, 'hello', 4, 5, 6, 7, 1, 'a']

    for v in list1:
        print(v)

带索引遍历

    list1 = [True, 2, 'hello', 4, 5, 6, 7, 1, 'a']

    # 转化为带索引的遍历
    for i, v in enumerate(list1):
        print("{}={}".format(i, v))

字典操作相关

  • 两个字典合并
    d1 = {"a": 1, "b": 2}
    d2 = {"de": "ad", "da2": 89}
    print(dict(d1, **d2))

    d3 = dict()
    d3.update(d1)
    d3.update(d2)
    print(d3)
    
    # 输出结果均为 {'a': 1, 'b': 2, 'de': 'ad', 'da2': 89}

加密相关

  • md5
 import hashlib
 data = "hello中国"
 hashlib.md5(data.encode(encoding='UTF-8')).hexdigest()

zip()用法

用来生成新的元组zip对象,入参iterables为可迭代的对象。例如str、list、dict,当各元素长度不一致时以最短的元素长度为准,生成新zip对象

如下源代码注释(python版本3.9.4):

class zip(object):
    """
    zip(*iterables) --> A zip object yielding tuples until an input is exhausted.
    
       >>> list(zip('abcdefg', range(3), range(4)))
       [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]
    
    The zip object yields n-length tuples, where n is the number of iterables
    passed as positional arguments to zip().  The i-th element in every tuple
    comes from the i-th iterable argument to zip().  This continues until the
    shortest argument is exhausted.
    """
  • 示例

        dict1 = {"platform": "taobao", "method": "get", "method_name": "order_list"}  # 长度3
        list1 = [1, 2, True, 4]  # 长度4
        str1 = "test_zip"  # 长度8
    
        z = zip(dict1, list1, str1)
    
        print(f'类型:{type(z)}, 值:{z}, 可视化结果: {list(z)}')
       
      	输出结果:
        类型:<class 'zip'>, 值:<zip object at 0x106e809c0>, 可视化结果: [('platform', 1, 't'), ('method', 2, 'e'), ('method_name', True, 's')]
    
  • 通常用于一一对应数值转化(示例)

        list1 = ["https://www.baidu.com", "https://www.taobao.com", "http://www.jd.com"]  # 长度3
        context = ['<html>1111</html>', '<html>222</html>', '<html>333</html>']
        z = zip(list1, context)
        print(f'类型:{type(z)}, 值:{z}, 可视化结果: {list(z)}')
        
        # 输出结果
        # 类型:<class 'zip'>, 值:<zip object at 0x10564b980>, 可视化结果: [('https://www.baidu.com', '<html>1111</html>'), ('https://www.taobao.com', '<html>222</html>'), ('http://www.jd.com', '<html>333</html>')]
    
    
  • 当入参为[]时返回结果也是空zi p对象

        z = zip() # 或 z = zip([])
        print(f'类型:{type(z)}, 值:{z}, 可视化结果: {list(z)}')
        # 类型:<class 'zip'>, 值:<zip object at 0x10a0f9280>, 可视化结果: []
    

requests使用注意事项

  • requests传入cookies时,必须所有参数值都是字符串(即使是数值也要转成str)

    示例:

    cookies = {"uid":"12345","accountType":"1"}
    # 使用
    requests.get(url,cookies = cookies, headers = headers)
    

mongo相关

  • mongo批量操作存在更新否则插入
import datetime
from pymongo import ReplaceOne
def save_data(list):
    result = []
    for item in list:
        item["update_time"] = datetime.datetime.now()
        item['date'] = datetime.datetime.now()
        # ReplaceOne()第一个参数放过滤条件,比如根据ID更新,则放ID,更加订单号order_no则,放置order_no
        result.append(ReplaceOne({'id': item['id']}, item, upsert=True))

    if len(result) > 0:
        res = collection.bulk_write(result)

python实现定时任务

博客

flask启动配置相关

需要外网访问则host为0:0:0:0

app.run(host='0.0.0.0', port=8080)
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值