71 lines
1.6 KiB
Python
71 lines
1.6 KiB
Python
# 创建字符串
|
||
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)
|