Python 基础知识:字符串(str)
作者:野牛程序员:2025-12-22 09:20:40python阅读 1998
Python 基础知识:字符串(str)
# /*
# Python 基础知识:字符串(str)
# --------------------------------------------------------
# 功能:
# 1) 演示字符串的创建、访问、操作与常用方法
# 2) 展示多行字符串、转义字符、格式化输出
# 3) 说明字符串不可变特性及切片用法
# */
# ========================================
print("示例一:字符串创建与类型检查")
s1 = "Hello"
s2 = 'World'
s3 = """这是
多行
字符串"""
print("s1 =", s1, "类型:", type(s1))
print("s2 =", s2, "类型:", type(s2))
print("s3 =", s3, "类型:", type(s3))
print("-" * 40)
# ========================================
print("示例二:转义字符与原始字符串")
s4 = "第一行\n第二行\t缩进"
print("普通转义字符:\n", s4)
raw_s = r"C:\Users\Name\Desktop"
print("原始字符串:", raw_s)
print("-" * 40)
# ========================================
print("示例三:字符串拼接与重复")
a = "Python"
b = "3"
print("拼接:", a + b)
print("重复:", a * 3)
print("-" * 40)
# ========================================
print("示例四:字符串索引与切片")
text = "Hello Python"
print("text[0] =", text[0])
print("text[-1] =", text[-1])
print("text[0:5] =", text[0:5]) # 前闭后开
print("text[6:] =", text[6:])
print("text[:5] =", text[:5])
print("text[::2] =", text[::2]) # 步长为2
print("-" * 40)
# ========================================
print("示例五:常用方法演示")
s = " hello world "
print("原始字符串:", s)
print("去除首尾空格:", s.strip())
print("全部大写:", s.upper())
print("全部小写:", s.lower())
print("首字母大写:", s.capitalize())
print("查找 'world' 索引:", s.find("world"))
print("替换 'hello' -> 'hi':", s.replace("hello", "hi"))
print("分割:", s.split())
print("连接:", "-".join(["a","b","c"]))
print("-" * 40)
# ========================================
print("示例六:格式化字符串")
name = "Alice"
age = 25
# %-格式化
print("姓名: %s, 年龄: %d" % (name, age))
# str.format()
print("姓名: {}, 年龄: {}".format(name, age))
# f-string (Python 3.6+)
print(f"姓名: {name}, 年龄: {age}")
# ========================================
# 要点总结:
# 1) 字符串是不可变序列,修改会生成新对象;
# 2) 支持单引号、双引号、三引号创建,三引号支持多行;
# 3) 转义字符用 \,原始字符串用 r"..." 避免转义;
# 4) 支持拼接 +、重复 *、索引和切片操作;
# 5) 常用方法有 strip、upper、lower、capitalize、find、replace、split、join 等;
# 6) 字符串格式化有 %-格式化、str.format() 和 f-string。
# */
# 示例一:字符串创建与类型检查
# s1 = Hello 类型: <class 'str'>
# s2 = World 类型: <class 'str'>
# s3 = 这是
# 多行
# 字符串 类型: <class 'str'>
# ----------------------------------------
# 示例二:转义字符与原始字符串
# 普通转义字符:
# 第一行
# 第二行 缩进
# 原始字符串: C:\Users\Name\Desktop
# ----------------------------------------
# 示例三:字符串拼接与重复
# 拼接: Python3
# 重复: PythonPythonPython
# ----------------------------------------
# 示例四:字符串索引与切片
# text[0] = H
# text[-1] = n
# text[0:5] = Hello
# text[6:] = Python
# text[:5] = Hello
# text[::2] = HloPto
# ----------------------------------------
# 示例五:常用方法演示
# 原始字符串: hello world
# 去除首尾空格: hello world
# 全部大写: HELLO WORLD
# 全部小写: hello world
# 首字母大写: hello world
# 查找 'world' 索引: 7
# 替换 'hello' -> 'hi': hi world
# 分割: ['hello', 'world']
# 连接: a-b-c
# ----------------------------------------
# 示例六:格式化字符串
# 姓名: Alice, 年龄: 25
# 姓名: Alice, 年龄: 25
# 姓名: Alice, 年龄: 25野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

