一、使用IDEA创建Python项目

文件-新建-项目,语言选择Python,等待python解释器安装成功后即可

二、Python语法基础

import subprocess
import re
import os
from pathlib import Path

subprocess.run("dir", shell=True, encoding='utf8')
print("hello")
name = "zhangsan"
# name:  zhangsan
print(f"name:  {name}")
# zhangsan
print(name)

name2 = "zhangsann"
# False
print(name == name2)

# 从外部输入
high = input("please input high:")
print(f"high: {high}")

# False
print("A" == 65)
print("A" + "1")

# 读取外部文件内容
try:
    with open("firsttxt.txt", "r", encoding='utf-8') as f:
        content = f.read()
        print(content)
except FileNotFoundError:
    print("file not found")
finally:
    print("try end")

# 条件判断
if 8 == 10:
    print(等于)
else:
    print("不等于")

# 循环
for i in {1, 2, 3, 4}:
    print(i)

# 检查数据类型
f = 0.22
#<class 'float'>
print(type(f))

str = "hello python"
# <class 'str'>
print(type(str))

num = 22;
# <class 'int'>
print(type(num))

# []列表是一个有序、可变的序列容器
list = [1, 2, 3, 4]
list.append(7)
# <class 'list'>
print(type(list))
#()tuple元组不可变
list2 = ("w", "w", "3")
# <class 'tuple'>
print(type(list2))
b = True
# <class 'bool'>
print(type(b))
map = {"name": "haha", "age": 22} \
    # <class 'dict'>
print(type(map))
# 打印所有key。dict_keys(['name', 'age'])
print(map.keys())
# 打印所有value。dict_values(['haha', 22])
print(map.values())
# 打印所有key和value。dict_items([('name', 'haha'), ('age', 22)])
print(map.items())

#定义类,实例化对象
class Dog:
    def __init__(self, name: object, age: object) -> object:
        self.name = name
        self.age = age

    def bark(self):
        return self.name
dog = Dog("haha", 22)
print(dog.bark())

"""
\d:匹配任意一个数字 (0-9)。
\w:匹配字母、数字或下划线 (A-Z, a-z, 0-9, _)。
.:匹配除换行符以外的任意单个字符。
+:匹配前面的字符至少出现 1 次(例如 \d+ 就能匹配 123 这样的一串数字)。
*:匹配前面的字符出现 0 次或多次。
"""
#re正则匹配
str = "sjsj88snn 22j"
#<re.Match object; span=(4, 6), match='88'>
print(re.search(r"\d+",str))
#sjsj22snn 22j
print(re.sub(r"88","22",str))
#['88', '22']
print(re.findall(r"\d+", str))

if os.path.isfile("firsttxt.txt"):
    print("firsttxt.txt is exists")
if os.path.isdir("sss"):
    print("dir is exists")
else:
    print("dir is not exists")

path = Path("firsttxt.txt")
print(path)
#读取文件内容
print(path.read_text())
#写入文件内容
path.write_text("20260523")

print(path.read_text())

更多推荐