59 lines
1.2 KiB
Python
59 lines
1.2 KiB
Python
# 1. 字符串大小写转换
|
|
text = "Hello, World!"
|
|
# 将字符串转换为全大写
|
|
upper_text = text.upper()
|
|
print(upper_text)
|
|
# 将字符串转换为全小写
|
|
lower_text = text.lower()
|
|
print(lower_text)
|
|
# 将字符串首字母大写
|
|
capitalized_text = text.capitalize()
|
|
print(capitalized_text)
|
|
|
|
# 2. 字符串查找和替换
|
|
text = "Hello, World! Hello, Python!"
|
|
# 查找子字符串的位置
|
|
index = text.find("World")
|
|
print(index)
|
|
# 替换子字符串
|
|
new_text = text.replace("Hello", "Hi")
|
|
print(new_text)
|
|
|
|
# 3. 字符串分割和连接
|
|
text = "apple,banana,orange"
|
|
# 分割字符串
|
|
fruits = text.split(",")
|
|
print(fruits)
|
|
# 连接字符串
|
|
joined_text = "-".join(fruits)
|
|
print(joined_text)
|
|
|
|
# 4. 字符串去除空白字符
|
|
text = " Hello, World! "
|
|
# 去除字符串左侧的空白字符
|
|
left_stripped = text.lstrip()
|
|
print(left_stripped)
|
|
# 去除字符串右侧的空白字符
|
|
right_stripped = text.rstrip()
|
|
print(right_stripped)
|
|
# 去除字符串两侧的空白字符
|
|
stripped = text.strip()
|
|
print(stripped)
|
|
|
|
# 5. 字符串判断
|
|
text = "12345"
|
|
# 判断字符串是否由数字组成
|
|
is_digit = text.isdigit()
|
|
print(is_digit)
|
|
text = "Hello"
|
|
# 判断字符串是否由字母组成
|
|
is_alpha = text.isalpha()
|
|
print(is_alpha)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|