当前位置: 首页 > 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 + bTypeError: 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) + 1print(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 += charreturn resultencrypted = 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 Noneprint(is_valid_email("test@example.com"))  # True

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

from string import Templatet = 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 入门绘图库
🐳 🐋 🐬


http://www.mrgr.cn/news/98041.html

相关文章:

  • 【后端开发】初识Spring IoC与SpringDI、图书管理系统
  • 力扣热题100刷题day63|49.字母异位词分组
  • C++指针(四)万字图文详解!
  • 嵌入式MCU常用模块
  • C语言:位段
  • MCP基础学习四:MCP在AI应用中的集成(MCP在AI应用中的完整架构图)
  • 面试题之网络相关
  • 算法驱动的场景识别:规则引擎与机器学习的强大结合
  • C++中作用域public,private,protected说明
  • SSRF打靶总结
  • 浅析Centos7安装Oracle12数据库
  • 《计算机名人堂》专栏介绍:先驱之路
  • leetcode 322. Coin Change
  • VMware虚拟机Ubuntu磁盘扩容
  • 【教学类-102-08】剪纸图案全套代码08——Python点状虚线优化版本02(有空隙)+制作1图2图6图24图
  • MySQL 进阶 - 2 ( 15000 字详解)
  • 蓝桥杯补题
  • ubuntu22.04下安装mysql以及mysql-workbench
  • ctfshow web入门 web42
  • opencv-python基础