问1:请对下列字符串进行操作:
str1 = "Hello World!"
print(str1)
print(str1[0:-1])
print(str1[-1])
print(str1[2:5])
print(str1[2:])
print(str1*2)
参考答案请见评论区。
Python 提供了丰富的字符串操作功能,包括连接、切片、查找、替换、分割、大小写转换等。下面是一些常见的 Python 字符串操作示例:
1. 连接字符串
str1 = "Hello"
str2 = "World"
str3 = str1 + " " + str2 # 使用加号连接字符串
print(str3) # 输出: Hello World
2. 字符串切片
s = "Python is fun"
print(s[0:5]) # 输出: Pytho
print(s[6:]) # 输出: is fun
print(s[-1]) # 输出: n
字符串使用方括号[ ]来截取字符串,其基本语法如下:
变量[头下标:尾下标],其中下标最小的索引值以0为开始值,-1为从末尾的开始位置。
3. 查找字符串
s = "Hello World"
index = s.find("World") # 查找子字符串的位置
if index != -1:
print("Found at index:", index) # 输出: Found at index: 6
else:
print("Not found")
4. 替换字符串
s = "Hello World"
new_s = s.replace("World", "Python") # 替换子字符串
print(new_s) # 输出: Hello Python
5. 分割字符串
s = "apple,banana,cherry"
fruits = s.split(",") # 使用逗号分割字符串
print(fruits) # 输出: ['apple', 'banana', 'cherry']
6. 大小写转换
s = "hello world"
upper_s = s.upper() # 转换为大写
lower_s = s.lower() # 转换为小写
print(upper_s) # 输出: HELLO WORLD
print(lower_s) # 输出: hello world
7. 去除字符串两边的空格
s = " Hello World "
s_stripped = s.strip() # 去除字符串两边的空格
print(s_stripped) # 输出: Hello World
8. 判断字符串开头或结尾
s = "HelloWorld"
print(s.startswith("Hello")) # 输出: True
print(s.endswith("World")) # 输出: True
9. 字符串格式化
name = "Alice"
age = 30
formatted_str = "My name is {} and I am {} years old.".format(name, age)
print(formatted_str) # 输出: My name is Alice and I am 30 years old.
10. 使用 f-string 格式化(Python 3.6+)
name = "Alice"
age = 30
formatted_str = f"My name is {name} and I am {age} years old."
print(formatted_str) # 输出: My name is Alice and I am 30 years old.