From 3fd32ff683f9b0e202998418304c6d914e8065db Mon Sep 17 00:00:00 2001 From: Henry Lin Date: Wed, 27 Aug 2025 15:57:48 +0800 Subject: [PATCH] Add string demo --- 0002_3/string.py | 70 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 0002_3/string.py diff --git a/0002_3/string.py b/0002_3/string.py new file mode 100644 index 0000000..1516aaf --- /dev/null +++ b/0002_3/string.py @@ -0,0 +1,70 @@ +# 创建字符串 +greeting = "Hello, World!" +print(greeting) + +# 示例代码 +text = "Hello, World!" + +# 字符串长度 +length = len(text) +print(length) # 输出:13 + +# 字符串拼接 +concatenated = text + " Welcome!" +print(concatenated) # 输出:Hello, World! Welcome! + +# 字符串复制 +repeated = text * 3 +print(repeated) # 输出:Hello, World!Hello, World!Hello, World! + +# 字符串索引 +first_char = text[0] +print(first_char) # 输出:H + +# 字符串切片 +substring = text[7:12] +print(substring) # 输出:World + +# 大小写转换 +lowercase = text.lower() +uppercase = text.upper() +print(lowercase) # 输出:hello, world! +print(uppercase) # 输出:HELLO, WORLD! + +# 字符串查找 +position = text.find("World") +print(position) # 输出:7 + +# 字符串替换 +replaced = text.replace("World", "Python") +print(replaced) # 输出:Hello, Python! + +# 去除空白 +trimmed = " Hello, World! ".strip() +print(trimmed) # 输出:Hello, World! + +# 分割字符串 +words = text.split(", ") +print(words) # 输出:['Hello', 'World!'] + + +""" +基础:编写一个Python程序,将字符串 “Python” 转换为全大写并打印出来。 +""" +str_1 = "Python" +new_str_1 = str_1.upper() +print(new_str_1) + +""" +应用:给定字符串 “Hello, Python!”,使用字符串查找方法找出 “Python” 在该字符串中的位置。 +""" +str_2 = "Hello, Python!" +index = str_2.find("Python") +print(index) + +""" +挑战:编写一个Python程序,将字符串 “Hello, World!” 中的 “World” 替换为 “Python”,并将结果打印出来。 +""" +str_3 = "Hello, World!" +new_str_3 = str_3.replace("World", "Python") +print(new_str_3)