# Python字符串的操作方法
# 1. 字符串的创建
# 创建一个简单的字符串
string_example = "Hello, World!"
print(string_example) # 输出: Hello, World!
# 2. 字符串的拼接
# 使用 + 运算符拼接字符串
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # 输出: Hello World
# 3. 字符串的索引和切片
# 索引从0开始,支持负数索引
my_string = "Python"
print(my_string[0]) # 输出: P
print(my_string[-1]) # 输出: n
# 切片操作 [start:end:step]
print(my_string[1:4]) # 输出: yth
print(my_string[::-1]) # 输出: nohtyP (反转字符串)
# 4. 字符串的常用方法
# 转换为大写
upper_case = my_string.upper()
print(upper_case) # 输出: PYTHON
# 转换为小写
lower_case = my_string.lower()
print(lower_case) # 输出: python
# 去除首尾空格
stripped_string = " Hello, World! ".strip()
print(stripped_string) # 输出: Hello, World!
# 替换子字符串
replaced_string = "Hello, World!".replace("World", "Python")
print(replaced_string) # 输出: Hello, Python!
# 检查字符串是否以指定字符开头或结尾
starts_with_hello = "Hello, World!".startswith("Hello")
ends_with_world = "Hello, World!".endswith("World!")
print(starts_with_hello) # 输出: True
print(ends_with_world) # 输出: True
# 分割字符串
split_string = "apple,banana,cherry".split(",")
print(split_string) # 输出: ['apple', 'banana', 'cherry']
# 格式化字符串
formatted_string = "My name is {}, and I am {} years old.".format("Alice", 30)
print(formatted_string) # 输出: My name is Alice, and I am 30 years old.
# f-string (Python 3.6+)
name = "Bob"
age = 25
f_string = f"My name is {name}, and I am {age} years old."
print(f_string) # 输出: My name is Bob, and I am 25 years old.
上一篇:python的for循环
下一篇:python中split
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站