python-字符串
文章目录
- 创建字符串
- 字符串基本操作
- 访问字符串元素
- 字符串切片
- 字符串连接
- 字符串重复
- 字符串常用方法
- 大小写转换
- 查找和替换
- 分割和连接
- 去除空白字符
- 字符串格式化
- 字符串检查方法
- 字符串编码
- 转义字符
- 原始字符串
字符串(String)是 Python 中最常用的数据类型之一,用于表示文本信息。
创建字符串
Python 中的字符串可以用单引号(‘)、双引号(")或三引号(’''或"“”)创建:
# 单引号字符串
str1 = 'Hello World'# 双引号字符串
str2 = "Python Programming"# 三引号字符串(多行字符串)
str3 = """这是一个
多行字符串
示例"""str4 = '''这是一个
多行字符串
示例'''
字符串基本操作
访问字符串元素
s = "Python"
print(s[0]) # 输出: 'P' (索引从0开始)
print(s[-1]) # 输出: 'n' (负索引表示从末尾开始)
字符串切片
s = "Programming"
print(s[2:5]) # 输出: 'ogr' (从索引2到5-1)
print(s[:6]) # 输出: 'Progra' (从开始到索引6-1)
print(s[3:]) # 输出: 'gramming' (从索引3到末尾)
print(s[::2]) # 输出: 'Pormig' (步长为2)
字符串连接
s1 = "Hello"
s2 = "World"
print(s1 + " " + s2) # 输出: 'Hello World'
字符串重复
print("Hi" * 3) # 输出: 'HiHiHi'
字符串常用方法
大小写转换
s = "Python"
print(s.upper()) # 输出: 'PYTHON'
print(s.lower()) # 输出: 'python'
print(s.capitalize()) # 第一个字母大写,后面的字母全部小写
print(s.swapcase()) # 字母大小写互换
print(s.title()) # 每个单词首字母大写,字母之间存在非字母字符则判定为一个单词
查找和替换
s = "hello world"
print(s.find("world")) # 输出: 6 (返回索引位置)
print(s.replace("world", "Python")) # 输出: 'hello Python'
分割和连接
s = "apple,banana,orange"
print(s.split(",")) # 输出: ['apple', 'banana', 'orange']lst = ["Python", "Java", "C++"]
print(",".join(lst)) # 输出: 'Python,Java,C++'
去除空白字符
s = " Python "
print(s.strip()) # 输出: 'Python' (去除两端空格)
print(s.lstrip()) # 输出: 'Python ' (去除左端空格)
print(s.rstrip()) # 输出: ' Python' (去除右端空格)
字符串格式化
# 使用format方法
print("{} is {}".format("Python", "awesome")) # 输出: 'Python is awesome'# f-string (Python 3.6+)
name = "Alice"
age = 25
print(f"My name is {name} and I'm {age} years old.")
字符串检查方法
s = “Python123”
print(s.isalpha()) # False (是否全字母)
print(s.isdigit()) # False (是否全数字)
print(s.isalnum()) # True (是否字母或数字)
print(s.startswith("Py")) # True (是否以指定字符串开头)
print(s.endswith("123")) # True (是否以指定字符串结尾)
字符串编码
Python 3 默认使用 Unicode 编码(UTF-8):
s = "你好"
print(len(s)) # 输出: 2 (字符数)
print(s.encode()) # 输出: b'\xe4\xbd\xa0\xe5\xa5\xbd' (字节表示),以utf-8的编码打印出结果
转义字符
常用转义字符:
1、\n - 换行
2、\t - 制表符
3、\ - 反斜杠
4、’ - 单引号
5、" - 双引号
print("Line1\nLine2") # 输出两行文本
print("He said, \"Hello\"") # 输出: He said, "Hello"
原始字符串
在字符串前加 r 或 R 表示原始字符串,转义字符不会被特殊处理:
print(r"C:\new\folder") # 输出: C:\new\folder
print(R"C:\new\folder") # 输出: C:\new\folder