python 字符串切割例题_Python字符串及练习题

本文介绍了Python字符串的命名规则、定义方式、转义符号、索引与切片、成员操作符、开头和结尾匹配、变量名判断、搜索与替换、删除无用字符、对齐方法、统计功能、分离与连接、内置方法以及字符串实践题目,涵盖字符串的各个方面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.变量名命名规则

# 中文是可以作为变量名的,但不建议姓名 = "hello"print(姓名)# 变量名可以由字母,数字或者下划线;# 变量名只能以字母或者下划线组成;# 变量名不能是python的关键字: eg: if, elif, else,#   eg: while, for, break,continue,passa_1hello = "hello"print(a_1hello)# hell@ = "hello"# if = "hello"# while = "hello"

# break = "hello"

2.字符串的定义方式

字符串常用的转义符号:#   \n:换行#   \t: 一个tab键#   \': '#   \": "# 打印"hello"# 打印guido's# 打印"hello guido's python"print('"hello"')print("guido's")print("\"hello guido\'s python\"")

print("%s\t%s" % ("hello", "world"))

s = "hello"# 索引: 0,1,2,3,4, 索引值是从0开始的;print(s[0])print(s[4])print(s[-1])        # 拿出字符串的最后一个子符;# 切片print(s[0:3])       # 切片时规则为s[start:end:step],从start开始,到end-1结束, 步长为step;print(s[0:4:2])print(s[:])             # 显示所有子符print(s[:3])            # 显示前3个子符print(s[::-1])          # 对于字符串倒序输出;print(s[1:])            # 除了第一个子符之外, 其他全部显示;# 重复print(s*10)# 连接print("hello "+"world")# 成员操作符 s = "hello", in, not inprint('he' in s)print('aa' in s)

print('he' not in s)

字符串开头和结尾的匹配

# 找出字符串是否以xxxx结尾;s = "hello.jpg"print(s.endswith(('.png', '.jpg')))url1 = "http://www.baidu.com"url2 = "file:///mnt"url3 = "https://www.baidu.com"url4 = "ftp://www.baidu.com"# 以什么开头;print(url1.startswith(('https://', 'http://')))

print(url2.startswith("file://"))

字符串变量名判断

#[[:digit:]]#[[:upper:]]#[[:lower:]]#[[:alnum:]]#[[:space:]]s = 'hello'# 判断字符串里面的每个元素是否为什么类型, 一旦有一个元素不满足, 返回False;print("123".isdigit())print("123hfjhre".isdigit())print("HELLO".isupper())print("HELlO".isupper())# title是标题, 判断某个字符串是否为标题, 第一个字母为大写,其他为小写;p

### Python 字符串格式化 示例 练习题 以下是几个关于 Python 字符串格式化的练习题目,涵盖了 `%` 格式化、`str.format()` 方法以及 `f-string` 的应用。 #### 目一:基本字符串插值 编写一段程序,定义两个变量分别存储姓名和年龄,使用三种不同的方法(`%` 格式化、`str.format()` 和 `f-string`),将它们组合成如下形式的字符串:“我的名字是 [姓名],我今年 [年龄] 岁。” ```python name = "Alice" age = 25 # 使用 % 格式化 result_percent = "我的名字是 %s,我今年 %d 岁。" % (name, age) # 使用 str.format() result_format = "我的名字是 {}, 我今年 {} 岁。".format(name, age) # 使用 f-string result_fstring = f"我的名字是 {name}, 我今年 {age} 岁。" print(result_percent) # 输出结果应为 “我的名字是 Alice,我今年 25 岁。” print(result_format) # 同上 print(result_fstring) # 同上 ``` --- #### 目二:数值精度控制 给定一个浮点数 `pi=3.1415926`,将其格式化为保留两位小数的形式,并通过不同方法实现。 ```python pi = 3.1415926 # 使用 % 格式化 formatted_pi_percent = "%.2f" % pi # 使用 str.format() formatted_pi_format = "{:.2f}".format(pi) # 使用 f-string formatted_pi_fstring = f"{pi:.2f}" print(formatted_pi_percent) # 应输出 '3.14' print(formatted_pi_format) # 应输出 '3.14' print(formatted_pi_fstring) # 应输出 '3.14' ``` --- #### 目三:表格对齐 假设有一个商品列表及其价格,尝试使用字符串格式化来打印一张整齐的商品表,其中商品名称左对齐,价格右对齐并保留两位小数。 ```python items = [("苹果", 3.5), ("香蕉", 2.0), ("橙子", 4.8)] for item, price in items: # 使用 %-格式化 result_percent = "%-10s %.2f元" % (item, price) # 使用 str.format() 并指定宽度 result_format = "{:<10} {:.2f}元".format(item, price) # 使用 f-string 并指定宽度 result_fstring = f"{item:<10} {price:.2f}元" print(result_percent) # 输出示例:"苹果 3.50元" print(result_format) # 同上 print(result_fstring) # 同上 ``` --- #### 目四:日期时间格式化 已知当前时间为 `import datetime; now=datetime.datetime.now()`,请利用字符串格式化功能,将时间显示为以下两种样式: 1. **标准格式**:YYYY-MM-DD HH:MM:SS 2. **自定义格式**:今天是星期 X,现在的时间是 XX 小时 XX 分钟 提示:可以结合 `datetime.strftime()` 函数完成此任务。 ```python from datetime import datetime now = datetime.now() # 标准格式 standard_time = now.strftime("%Y-%m-%d %H:%M:%S") # 自定义格式 custom_time = f"今天是星期 {now.strftime('%A')[:1]},现在的时间是 {now.hour} 小时 {now.minute} 分钟" print(standard_time) # 输出类似于 "2023-10-07 14:30:00" print(custom_time) # 输出类似于 "今天是星期 S,现在的时间是 14 小时 30 分钟" ``` --- #### 目五:复杂表达式的嵌套 计算圆周率近似值 `(22 / 7)`,并将该值插入到一句话中,“π 近似等于 [值]”。要求保留四位小数。 ```python approx_pi = 22 / 7 # 使用 %-格式化 result_percent = "π 近似等于 %.4f" % approx_pi # 使用 str.format() result_format = "π 近似等于 {:.4f}".format(approx_pi) # 使用 f-string result_fstring = f"π 近似等于 {approx_pi:.4f}" print(result_percent) # 输出 "π 近似等于 3.1429" print(result_format) # 同上 print(result_fstring) # 同上 ``` --- ### 总结 以上练习覆盖了常见的字符串格式化场景,包括简单的变量替换、数值精度调整、对齐操作以及复杂的表达式嵌套[^1][^2]。这些技能对于日常编程非常实用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值