1. 字符串基础操作
1.1 字符串创建与基本概念
python中的字符串是不可变序列,可以使用单引号、双引号或三引号创建:
# 单引号创建字符串 str1 = 'hello world' print(str1) # 输出:hello world # 双引号创建字符串 str2 = "python programming" print(str2) # 输出:python programming # 三引号创建多行字符串 str3 = '''这是 多行 字符串''' print(str3)
1.2 字符串拼接与重复
# 字符串拼接 name = "张三" greeting = "你好," + name + "!" print(greeting) # 输出:你好,张三! # 字符串重复 stars = "*" * 10 print(stars) # 输出:**********
2. 字符串格式化方法
2.1 f-string格式化(推荐使用)
f-string是python 3.6引入的高效格式化方法:
# 基本用法
name = "李四"
age = 25
info = f"姓名:{name},年龄:{age}"
print(info) # 输出:姓名:李四,年龄:25
# 表达式求值
a, b = 10, 20
result = f"{a} + {b} = {a + b}"
print(result) # 输出:10 + 20 = 30
# 函数调用
def get_score():
return 95.5
score_info = f"考试成绩:{get_score()}分"
print(score_info) # 输出:考试成绩:95.5分 2.2 format()方法格式化
# 位置参数
template1 = "{}的{}成绩是{}分".format("小明", "数学", 98)
print(template1) # 输出:小明的数学成绩是98分
# 关键字参数
template2 = "姓名:{name},年龄:{age}".format(name="王五", age=30)
print(template2) # 输出:姓名:王五,年龄:30
# 数字格式化
pi = 3.1415926
formatted_pi = "圆周率:{:.2f}".format(pi)
print(formatted_pi) # 输出:圆周率:3.14 2.3 %格式化(传统方法)
# 基本格式化 name = "赵六" score = 88 info = "学生%s的成绩是%d分" % (name, score) print(info) # 输出:学生赵六的成绩是88分 # 浮点数格式化 price = 15.5 price_info = "价格:%.1f元" % price print(price_info) # 输出:价格:15.5元
3. 字符串索引与切片
3.1 字符串索引
text = "python编程" # 正向索引 print(text[0]) # 输出:p print(text[5]) # 输出:n # 负向索引 print(text[-1]) # 输出:程 print(text[-3]) # 输出:编
3.2 字符串切片
text = "hellopythonworld"
# 基本切片
print(text[0:5]) # 输出:hello
print(text[5:11]) # 输出:python
# 省略起始/结束位置
print(text[:5]) # 输出:hello
print(text[11:]) # 输出:world
# 使用步长
print(text[::2]) # 输出:hloptowrd
print(text[::-1]) # 输出:dlrownohtypolleh(反转字符串)
# 回文判断示例
def is_palindrome(s):
return s == s[::-1]
print(is_palindrome("racecar")) # 输出:true
print(is_palindrome("hello")) # 输出:false 4. 字符串常用方法
4.1 查找与替换方法
text = "python是一门强大的编程语言,python简单易学"
# 查找方法
print(text.find("python")) # 输出:0
print(text.rfind("python")) # 输出:16
print(text.index("编程")) # 输出:8
print("python" in text) # 输出:true
# 替换方法
new_text = text.replace("python", "java")
print(new_text) # 输出:java是一门强大的编程语言,java简单易学 4.2 大小写转换
text = "hello world" print(text.upper()) # 输出:hello world print(text.lower()) # 输出:hello world print(text.title()) # 输出:hello world print(text.capitalize()) # 输出:hello world
4.3 字符串分割与连接
# 分割字符串
data = "apple,banana,orange,grape"
fruits = data.split(",")
print(fruits) # 输出:['apple', 'banana', 'orange', 'grape']
# 连接字符串
new_data = "-".join(fruits)
print(new_data) # 输出:apple-banana-orange-grape
# 多行分割
multiline_text = "第一行
第二行
第三行"
lines = multiline_text.splitlines()
print(lines) # 输出:['第一行', '第二行', '第三行'] 4.4 去除空白字符
text = " hello world " print(text.strip()) # 输出:hello world print(text.lstrip()) # 输出:hello world print(text.rstrip()) # 输出: hello world
5. 字符串判断方法
# 各种判断方法示例
text1 = "hello123"
text2 = "12345"
text3 = "hello"
text4 = "hello"
text5 = "hello world"
print(text1.isalnum()) # 输出:true(字母或数字)
print(text2.isdigit()) # 输出:true(纯数字)
print(text3.isupper()) # 输出:true(全大写)
print(text4.islower()) # 输出:true(全小写)
print(text5.istitle()) # 输出:true(标题格式)
print(text1.startswith("hello")) # 输出:true
print(text1.endswith("123")) # 输出:true 6. 转义字符与原始字符串
6.1 常用转义字符
# 转义字符使用
print("hello
world") # 换行
print("hello\tworld") # 制表符
print("他说:\"你好\"") # 双引号
print('它说:\'你好\'') # 单引号
print("路径:c:\\users") # 反斜杠
6.2 原始字符串
# 原始字符串(不处理转义字符) path = r"c:\users\documents\file.txt" print(path) # 输出:c:\users\documents\file.txt regex_pattern = r"\d+\w*" print(regex_pattern) # 输出:\d+\w*
7. 字符串与数值转换
# 字符串转数字
num_str = "123"
num_int = int(num_str)
num_float = float("3.14")
print(f"整数:{num_int},浮点数:{num_float}") # 输出:整数:123,浮点数:3.14
# 数字转字符串
number = 42
str_number = str(number)
print(f"字符串:{str_number},类型:{type(str_number)}") # 输出:字符串:42,类型:<class 'str'> 8. 字符串编码与字节转换
# 字符串编码
text = "你好,世界"
utf8_bytes = text.encode('utf-8')
gbk_bytes = text.encode('gbk')
print(f"utf-8编码:{utf8_bytes}") # 输出:b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c'
print(f"gbk编码:{gbk_bytes}") # 输出:b'\xc4\xe3\xba\xc3\xa3\xac\xca\xc0\xbd\xe7'
# 字节解码
decoded_text = utf8_bytes.decode('utf-8')
print(f"解码后:{decoded_text}") # 输出:解码后:你好,世界 9. 字符串格式化高级应用
9.1 数字格式化控制
# 数字格式化示例
number = 1234.5678
print(f"千位分隔符:{number:,}") # 输出:1,234.5678
print(f"保留两位小数:{number:.2f}") # 输出:1234.57
print(f"百分比:{0.256:.1%}") # 输出:25.6%
print(f"十六进制:{255:#x}") # 输出:0xff 9.2 对齐与填充
# 字符串对齐
text = "python"
print(f"左对齐:|{text:<10}|") # 输出:|python |
print(f"右对齐:|{text:>10}|") # 输出:| python|
print(f"居中对齐:|{text:^10}|") # 输出:| python |
print(f"填充字符:|{text:*^10}|") # 输出:|**python**| 10. 综合应用实例
10.1 九九乘法表
# 使用字符串格式化输出九九乘法表
for i in range(1, 10):
for j in range(1, i + 1):
print(f"{j}×{i}={i*j:2d}", end=" ")
print() # 换行
10.2 打印三角形图案
# 打印三角形
def print_triangle(n):
for i in range(1, n + 1):
spaces = " " * (n - i)
stars = "*" * (2 * i - 1)
print(f"{spaces}{stars}")
print_triangle(5) # 输出5行三角形
10.3 字符串统计与分析
def analyze_string(text):
# 统计各种字符数量
total_chars = len(text)
letters = sum(1 for char in text if char.isalpha())
digits = sum(1 for char in text if char.isdigit())
spaces = sum(1 for char in text if char.isspace())
print(f"字符串:{text}")
print(f"总字符数:{total_chars}")
print(f"字母数:{letters}")
print(f"数字数:{digits}")
print(f"空格数:{spaces}")
analyze_string("hello world 123!") # 输出分析结果 总结
python字符串处理功能强大且灵活,通过掌握上述各种方法和技巧,可以高效地处理文本数据。在实际开发中,建议优先使用f-string进行字符串格式化,结合切片、查找替换等方法,能够满足绝大多数字符串处理需求。字符串的不可变性保证了数据的安全性,而丰富的内置方法则提供了便捷的操作方式。
参考来源
- python的max、min函数的用法及实例
- python: 格式化字符串f()用法
- python中切片的用法
- python用法第一篇:print的用法。
- python字符串的格式化
- python用法字符串_python字符串,详细用法补充
到此这篇关于python字符串全解析从创建到实战应用小结的文章就介绍到这了,更多相关python字符串创建应用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论