Files

106 lines
2.9 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 第 1-7 课示例:字符串
#
# 本文件集中演示字符串索引、切片、遍历和常见方法。
# 建议运行后对照每段注释观察结果,不需要用户输入。
# 一、索引
# 正索引从 0 开始,负索引从 -1 开始倒数。
technology = "Python"
print(f"第一个字符:{technology[0]}")
print(f"最后一个字符:{technology[-1]}")
# 二、长度
# 空格和标点同样会计入字符串长度。
prompt = "Python Agent"
print(f"提示词长度:{len(prompt)}")
# 三、切片
# 切片包含开始索引,不包含结束索引。
print(f"前三个字符:{technology[0:3]}")
print(f"从索引 3 到末尾:{technology[3:]}")
print(f"反转字符串:{technology[::-1]}")
# 四、遍历字符串
# for 会依次取得字符串中的每一个字符。
for character in "Agent":
print(f"当前字符:{character}")
# 五、清理两侧空白并转换大小写
raw_text = " Python Agent "
clean_text = raw_text.strip()
lower_text = clean_text.lower()
upper_text = clean_text.upper()
print(f"清理结果:{clean_text}")
print(f"小写结果:{lower_text}")
print(f"大写结果:{upper_text}")
# 六、替换文本
# replace() 返回新字符串,不会直接修改原字符串。
old_goal = "学习 Java 开发"
new_goal = old_goal.replace("Java", "Python")
print(f"原目标:{old_goal}")
print(f"新目标:{new_goal}")
# 七、查找和统计
analysis_text = "Python Agent Python FastAPI"
contains_agent = "Agent" in analysis_text
python_position = analysis_text.find("Python")
python_count = analysis_text.count("Python")
print(f"是否包含 Agent{contains_agent}")
print(f"Python 首次出现位置:{python_position}")
print(f"Python 出现次数:{python_count}")
# 八、判断开头与结尾
file_name = "agent_service.py"
print(f"是否以 agent 开头:{file_name.startswith('agent')}")
print(f"是否为 Python 文件:{file_name.endswith('.py')}")
# 九、分割与连接
# split() 得到列表;列表将在下一课系统学习。
technology_text = "Python,FastAPI,Django"
technology_list = technology_text.split(",")
technology_path = " -> ".join(technology_list)
print(f"分割结果:{technology_list}")
print(f"连接结果:{technology_path}")
# 十、字符串判断方法
age_text = "18"
code_text = "Agent2026"
print(f"年龄是否全部为数字:{age_text.isdigit()}")
print(f"代码是否只包含字母和数字:{code_text.isalnum()}")
# 十一、方法链
# 先清理两侧空白,再统一转为小写。
raw_answer = " YES "
clean_answer = raw_answer.strip().lower()
print(f"标准化回答:{clean_answer}")
# 十二、转义字符和原始字符串
print("第一行\n第二行")
project_path = r"D:\Code\Python"
print(f"项目路径:{project_path}")
# 十三、f-string 数字格式
total_hours = 6.5
progress = 0.756
print(f"总时长:{total_hours:.2f} 小时")
print(f"完成率:{progress:.1%}")