当前位置: 首页 > news >正文

Python学习笔记(二)(字符串)

文章目录

  • 编写简单的程序
    • 一、标识符 (Identifiers)及关键字
      • 命名规则:
      • 命名惯例:
      • 关键字
    • 二、变量与赋值 (Variables & Assignment)
      • 变量定义:
      • 多重赋值:
      • 变量交换:(很方便哟)
    • 三、输入与输出 (Input & Output)
      • 输入:
      • 输出:
    • 四、数值 (Numbers)
      • 数值类型:
      • 数值运算:
    • 五、字符串 (Strings)
      • 字符串定义:
      • 字符串操作:
      • 字符串格式化:
      • 常用字符串函数
        • 1. 基本操作函数
      • 2. 判断类函数
      • 3. 分割和连接
      • 4. 格式化函数
    • 字符串应用实例
      • 1. 数据清洗
      • 2. 密码强度检查
      • 3. 文本分析
      • 4. 字符串加密
      • 5. URL处理
    • 高级字符串操作
      • 1. 正则表达式 (re模块)
      • 2. 字符串模板 (string.Template)
      • 3. 字符串对齐
    • 类型转换
    • 资源库

编写简单的程序

一、标识符 (Identifiers)及关键字

标识符是用于标识变量、函数、类、模块等对象的名字。

命名规则:

  1. 由字母、数字和下划线 _ 组成
  2. 不能以数字开头
  3. 区分大小写
  4. 不能是 Python 关键字(如 if, for, while 等)

命名惯例:

  • 变量名:小写字母,单词间用下划线 _ 连接(如 student_name
  • 常量名:全大写字母(如 MAX_VALUE
  • 类名:首字母大写的驼峰式(如 StudentInfo
  • 函数名:小写字母,单词间用下划线(如 calculate_average

关键字

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
注意:
“False”,“None”,“True”首字母都需要大写

Python 关键字详解

二、变量与赋值 (Variables & Assignment)

变量定义:

Python中变量在访问前,必须先绑定某个对象,即赋值,否则会报错。

x = 10              # 整数
name = "Alice"      # 字符串
is_valid = True     # 布尔值

多重赋值:

a, b, c = 1, 2, 3       # 同时赋值多个变量
x = y = z = 0           # 多个变量赋相同值

变量交换:(很方便哟)

a, b = b, a     # 交换两个变量的值

注意:

  • 使用换行符分隔,一般一行一条语句
  • 从第一列开始,前面不能有空格,否则会出现语法错误
  • “#”后为注释语句
a = 100
b = "21"
a + b

TypeError: unsupported operand type(s) for +: 'int' and 'str'
  • Python是一种强类型语言,只支持该类型允许的运算操作
  • a 指向整数类型对象,b指向字符串类型对象,整数类型数据和字符串类型数据不能接相加,即字符串类型数据不能自动转换为整数类型数据。

三、输入与输出 (Input & Output)

输入:

name = input("请输入你的名字:")        # 获取字符串输入
age = int(input("请输入你的年龄:"))    # 获取整数输入

输出:

print("Hello World")                    # 基本输出
print("Name:", name, "Age:", age)       # 多个参数
print(f"Name: {name}, Age: {age}")      # f-string (Python 3.6+)

注意:

  • input()函数语句只能得到文本(字符串)
  • eval()函数语句可以得到数字(输入“ABC”等无法转化为数字进行运算,会报错……)
  • Python中存在强制转换 int(),float()
  • sep:用来设定以什么字符间隔输出对象,默认为空格
  • end:用来设定以什么字符作为输出对象的结尾,默认换行符“\n”,也可以是其他字符

Python中的eval()函数详解

print('2025','5','5',sep='/')
print("the answer is ",end="") #使用end="",输出字符串不会换行
print(3+4)

运行结果:

2025/5/5
the answer is 7

四、数值 (Numbers)

数值类型:

  1. 整数 (int)10, -5, 0
  2. 浮点数 (float)3.14, -0.001, 2.0
  3. 复数 (complex)1+2j

数值运算:

# 基本运算
a = 10 + 3    # 加
b = 10 - 3    # 减
c = 10 * 3    # 乘
d = 10 / 3    # 除(返回浮点数)
e = 10 // 3   # 整除
f = 10 % 3    # 取余
g = 10 ** 3   # 幂运算

# 增强赋值
x += 1        # 等价于 x = x + 1

Python中的数值运算函数及math库详解

五、字符串 (Strings)

字符串定义:

s1 = '单引号字符串'
s2 = "双引号字符串"
s3 = """多行
字符串"""

字符串操作:

# 连接
full_name = first_name + " " + last_name

# 重复
line = "-" * 20

# 索引
first_char = s[0]        # 第一个字符
last_char = s[-1]        # 最后一个字符

# 切片
sub = s[2:5]            # 第3到第5个字符
every_second = s[::2]   # 每隔一个字符

# 常用方法
s.upper()       # 转为大写
s.lower()       # 转为小写
s.strip()       # 去除两端空白
s.split(",")    # 按分隔符分割
s.replace("a", "b")  # 替换字符

字符串格式化:

# 传统方式
"Name: %s, Age: %d" % ("Alice", 20)

# str.format()
"Name: {}, Age: {}".format("Alice", 20)

# f-string (Python 3.6+)
f"Name: {name}, Age: {age}"

常用字符串函数

1. 基本操作函数
# 长度计算
s = "Hello"
len(s)  # 返回5

# 大小写转换
s.upper()  # "HELLO"
s.lower()  # "hello"
s.capitalize()  # "Hello" 将字符串的首字母大写
s.title()  # "Hello" (对于多单词字符串会每个单词首字母大写)

# 查找和替换
s.find('e')  # 1 (返回首次出现的索引,找不到返回-1)
s.rfind('l') # 3 返回该字符串在字符串s中最后的位置,不存在返回 -1 
s.index('e')  # 1 (类似find 但找不到会抛出异常:substring not found)
s.rindex('i') # 3 返回该字符串在字符串s中最后的位置
s.count('l') # 2 返回一个字符串在另一个字符串中出现的次数,不存在则结果为 0
s.replace('l', 'L')  # "HeLLo"

# 去除空白字符 (不修改原字符串)
"  hello  ".strip()  # "hello" 移除字符串 开头,结尾 的指定字符。默认移除空白字符(包括空格、制表符 \t、换行符 \n 等)。
"  hello  ".lstrip()  # "hello  "仅移除字符串 开头 的指定字符。
"  hello  ".rstrip()  # "  hello"仅移除字符串 结尾 的指定字符。

补充链接:
Python中的strip()
Python中字符串分隔与连接函数

2. 判断类函数

s.isalpha()  # 是否全是字母
s.isdigit()  # 是否全是数字
s.isalnum()  # 是否字母或数字
s.isspace()  # 是否全是空白字符
s.startswith('He')  # True
s.endswith('lo')  # True

3. 分割和连接

# 分割
"a,b,c".split(',')  # ['a', 'b', 'c']
"a b c".split()  # ['a', 'b', 'c'] (默认按空白字符分割)
"a\nb\nc".splitlines()  # ['a', 'b', 'c']

# 连接
'-'.join(['a', 'b', 'c'])  # "a-b-c"

4. 格式化函数

# 旧式格式化
"Hello, %s!" % "world"  # "Hello, world!"

# str.format()
"Hello, {}!".format("world")  # "Hello, world!"

# f-string (Python 3.6+)
name = "world"
f"Hello, {name}!"  # "Hello, world!"

字符串应用实例

1. 数据清洗

# 清理用户输入
user_input = "  Some User Input  "
cleaned = user_input.strip().lower()
print(cleaned)  # "some user input"

2. 密码强度检查

def check_password(password):
    if len(password) < 8:
        return "密码太短"
    if not any(c.isupper() for c in password):
        return "需要至少一个大写字母"
    if not any(c.islower() for c in password):
        return "需要至少一个小写字母"
    if not any(c.isdigit() for c in password):
        return "需要至少一个数字"
    return "密码强度足够"

3. 文本分析

text = "Python is an amazing programming language. Python is versatile."

# 统计单词出现次数
words = text.lower().split()
word_count = {}
for word in words:
    word = word.strip('.,!?')  # 去除标点
    word_count[word] = word_count.get(word, 0) + 1

print(word_count)  # {'python': 2, 'is': 2, 'an': 1, ...}

4. 字符串加密

# 简单的凯撒密码
def caesar_cipher(text, shift):
    result = ""
    for char in text:
        if char.isupper():
            result += chr((ord(char) + shift - 65) % 26 + 65)
        elif char.islower():
            result += chr((ord(char) + shift - 97) % 26 + 97)
        else:
            result += char
    return result

encrypted = caesar_cipher("Hello, World!", 3)
print(encrypted)  # "Khoor, Zruog!"

5. URL处理

# 解析查询参数
url = "https://example.com/search?q=python&page=2"

def parse_query(url):
    query = url.split('?', 1)[1]
    params = query.split('&')
    return {p.split('=')[0]: p.split('=')[1] for p in params}

print(parse_query(url))  # {'q': 'python', 'page': '2'}

高级字符串操作

1. 正则表达式 (re模块)

import re

# 验证电子邮件格式
def is_valid_email(email):
    pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
    return re.match(pattern, email) is not None

print(is_valid_email("test@example.com"))  # True

2. 字符串模板 (string.Template)

from string import Template

t = Template('Hello, $name!')
print(t.substitute(name='World'))  # "Hello, World!"

3. 字符串对齐

s = "Python"
s.ljust(10)  # 'Python    '
s.rjust(10)  # '    Python'
s.center(10) # '  Python  '

类型转换

Python 类型转换详解

资源库

Python Turtle 入门绘图库
🐳 🐋 🐬

相关文章:

  • 有哪些反爬机制可能会影响Python爬取视频?如何应对这些机制?
  • C#结合SQLite数据库使用方法
  • Dynamics365 ExportPdfTemplateExportWordTemplate两个Action调用的body构造
  • CASAIM自动化智能检测系统在螺杆转子数字化检测应用
  • 使用 Datadog 和 Slack Alerts 监控 minikube
  • Linux安装Elasticsearch详细教程
  • 乳腺癌识别:双模型融合
  • 行销和随销的区别
  • 深入理解 WebMvcConfigurer:定制 Spring MVC 的核心接口
  • AI与深度伪造技术:如何识别和防范AI生成的假视频和假音频?
  • CentOS 系统磁盘扩容并挂载到根目录(/)的详细步骤
  • 24FIC
  • 【数学建模】(智能优化算法)天牛须算法(Beetle Antennae Search, BAS)详解与Python实现
  • 利用 RNN 预测股票价格:从数据处理到可视化实战
  • 人工智能之数学基础:复矩阵
  • 机器人零位标定修正流程介绍
  • ZFS 数据恢复:从误删修复到 RAIDZ 恢复,原生工具与第三方软件对比
  • 【图像处理】:opencv实现模糊图像处理和对比度增强
  • 宝马集团加速 ERP 转型和上云之旅
  • 项目实战——苍穹外卖
  • 免费邯郸网站建设/seo 页面链接优化
  • 泰安做网站优化/百度问答怎么赚钱
  • wordpress选择虚拟云主机/武汉网络优化知名乐云seo
  • 淮南网站建设/长沙sem培训
  • 用jq和ajax做能登陆注册的一个网站/网站运营工作的基本内容
  • 企业邮箱网易登录入口/最彻底的手机优化软件