文章目录
- 前言
- 一、字符串创建与基本操作
-
- [1. 创建字符串](#1. 创建字符串)
- [2. 字符串基本操作](#2. 字符串基本操作)
- 二、字符串索引与切片
-
- [1. 索引(Indexing)](#1. 索引(Indexing))
- [2. 切片(Slicing)](#2. 切片(Slicing))
- 三、字符串常用方法
-
- [1. 查找与替换方法](#1. 查找与替换方法)
- [2. 大小写转换](#2. 大小写转换)
- [3. 分割与连接](#3. 分割与连接)
- [4. 去除空白字符](#4. 去除空白字符)
- [5. 判断方法(返回布尔值)](#5. 判断方法(返回布尔值))
- 四、字符串格式化
-
- [1. f-string(Python 3.6+,推荐)](#1. f-string(Python 3.6+,推荐))
- [2. format()方法](#2. format()方法)
前言
本文介绍了字符串的创建和基本操作、字符串索引与切片、字符串常用方法和字符串的格式化知识要点。
一、字符串创建与基本操作
1. 创建字符串
Python中有多种创建字符串的方式:
python
python
# 1. 单引号
s1 = 'Hello World'
# 2. 双引号(可以包含单引号)
s2 = "It's a beautiful day"
# 3. 三引号(创建多行字符串)
s3 = '''这是第一行
这是第二行
这是第三行'''
s4 = """多行字符串
也可以这样写"""
# 4. 使用str()函数转换
num = 123
s5 = str(num) # "123"
2. 字符串基本操作
python
python
# 1. 连接(拼接)
s1 = "Hello" + " " + "World" # "Hello World"
# 2. 重复
s2 = "Hi" * 3 # "HiHiHi"
# 3. 获取长度
text = "Python"
length = len(text) # 6
# 4. 成员检查
print("P" in "Python") # True
print("thon" in "Python") # True
print("Java" in "Python") # False
二、字符串索引与切片
1. 索引(Indexing)
字符串中的每个字符都有位置索引:
python
python
text = "Python"
# 正向索引(从左到右)
# P y t h o n
# 0 1 2 3 4 5
# 反向索引(从右到左)
# P y t h o n
# -6 -5 -4 -3 -2 -1
print(text[0]) # "P"
print(text[2]) # "t"
print(text[-1]) # "n"(最后一个字符)
print(text[-3]) # "h"
2. 切片(Slicing)
切片用于获取字符串的一部分,语法:[起始:结束:步长]
python
python
text = "Python Programming"
# 基本切片
print(text[0:6]) # "Python"(索引0到5,不包括6)
print(text[7:18]) # "Programming"
print(text[:6]) # "Python"(省略起始,默认为0)
print(text[7:]) # "Programming"(省略结束,默认为末尾)
print(text[:]) # "Python Programming"(复制整个字符串)
# 使用步长
print(text[::2]) # "Pto rgamn"(每隔一个字符)
print(text[::-1]) # "gnimmargorP nohtyP"(反转字符串)
# 负数索引切片
print(text[-11:]) # "Programming"(从倒数第11个到末尾)
print(text[:-12]) # "Python"(从开始到倒数第12个)
# 常用切片技巧
filename = "document.pdf"
print(filename[-3:]) # "pdf"(获取文件扩展名)
三、字符串常用方法
1. 查找与替换方法
python
python
text = "Python is powerful. Python is easy."
# 查找
print(text.find("Python")) # 0(返回首次出现的索引)
print(text.rfind("Python")) # 19(从右向左查找)
print(text.find("Java")) # -1(未找到)
print(text.index("Python")) # 0(类似find,但未找到会报错)
print("Python" in text) # True(成员检查)
# 计数
print(text.count("Python")) # 2(出现次数)
print(text.count("is")) # 2
# 替换
new_text = text.replace("Python", "Java")
print(new_text) # "Java is powerful. Java is easy."
# 只替换指定次数
print(text.replace("Python", "Java", 1)) # 只替换第一个
2. 大小写转换
python
python
text = "Python Programming"
print(text.lower()) # "python programming"
print(text.upper()) # "PYTHON PROGRAMMING"
print(text.title()) # "Python Programming"(每个单词首字母大写)
print(text.capitalize()) # "Python programming"(仅首字母大写)
print(text.swapcase()) # "pYTHON pROGRAMMING"(大小写互换)
3. 分割与连接
python
python
# 分割
csv_data = "apple,banana,orange,grape"
fruits = csv_data.split(",") # ["apple", "banana", "orange", "grape"]
print(fruits[0]) # "apple"
# 按行分割
multi_line = "第一行\n第二行\n第三行"
lines = multi_line.splitlines() # ["第一行", "第二行", "第三行"]
# 指定分割次数
text = "one:two:three:four"
print(text.split(":", 2)) # ["one", "two", "three:four"](只分割前两次)
# 连接
words = ["Hello", "World", "!"]
sentence = " ".join(words) # "Hello World !"
path = "/".join(["usr", "local", "bin"]) # "usr/local/bin"
4. 去除空白字符
python
python
text = " Python "
print(text.strip()) # "Python"(去除两侧空白)
print(text.lstrip()) # "Python "(去除左侧空白)
print(text.rstrip()) # " Python"(去除右侧空白)
# 去除特定字符
text2 = "###Python###"
print(text2.strip("#")) # "Python"
5. 判断方法(返回布尔值)
python
python
s1 = "Python123"
s2 = "12345"
s3 = "PYTHON"
s4 = "python"
s5 = " "
s6 = "Hello World"
print(s1.isalnum()) # True(字母或数字)
print(s2.isdigit()) # True(全是数字)
print(s3.isupper()) # True(全大写)
print(s4.islower()) # True(全小写)
print(s5.isspace()) # True(全是空白字符)
print(s6.istitle()) # True(每个单词首字母大写)
print(s1.startswith("Py")) # True
print(s1.endswith("123")) # True
四、字符串格式化
1. f-string(Python 3.6+,推荐)
python
python
name = "Alice"
age = 25
score = 95.5678
# 基本使用
print(f"姓名:{name},年龄:{age}")
# 表达式计算
print(f"{name}明年{age + 1}岁")
# 格式控制
print(f"分数:{score:.2f}") # 保留2位小数:95.57
print(f"分数:{score:8.2f}") # 宽度8,右对齐: 95.57
print(f"分数:{score:<8.2f}") # 宽度8,左对齐:95.57
print(f"分数:{score:^8.2f}") # 宽度8,居中对齐: 95.57
# 数字格式
number = 1234567
print(f"{number:,}") # 千位分隔:1,234,567
print(f"{number:.2e}") # 科学计数法:1.23e+06
# 对齐与填充
print(f"{name:>10}") # 右对齐,宽度10:" Alice"
print(f"{name:*<10}") # 左对齐,*填充:"Alice*****"
print(f"{name:=^10}") # 居中对齐,=填充:"==Alice==="
2. format()方法
python
python
# 位置参数
print("{}的年龄是{}岁".format("Bob", 30)) # "Bob的年龄是30岁"
print("{1}的年龄是{0}岁".format(30, "Bob")) # "Bob的年龄是30岁"
# 关键字参数
print("{name}的成绩是{score}分".format(name="Alice", score=95))
# 格式控制(类似f-string)
print("分数:{:.2f}".format(95.5678)) # "分数:95.57"
print("数字:{:,}".format(1234567)) # "数字:1,234,567"
print("姓名:{:>10}".format("Alice")) # "姓名: Alice"