2025-08-27 15:57:48 +08:00

71 lines
1.6 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.

# 创建字符串
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)