# 示例代码:Python 中的字符串操作
# 创建字符串
my_string = "Hello, World!"
# 字符串长度
length = len(my_string)
print(f"字符串长度: {length}") # 输出: 字符串长度: 13
# 字符串拼接
greeting = "Hello"
name = "Alice"
message = greeting + ", " + name + "!"
print(message) # 输出: Hello, Alice!
# 字符串格式化
formatted_message = f"{greeting}, {name}!"
print(formatted_message) # 输出: Hello, Alice!
# 字符串方法
lowercase_message = my_string.lower() # 转换为小写
uppercase_message = my_string.upper() # 转换为大写
print(lowercase_message) # 输出: hello, world!
print(uppercase_message) # 输出: HELLO, WORLD!
# 查找子字符串
index = my_string.find("World")
print(f"'World' 的索引位置: {index}") # 输出: 'World' 的索引位置: 7
# 替换子字符串
replaced_message = my_string.replace("World", "Python")
print(replaced_message) # 输出: Hello, Python!
len() 函数获取字符串的长度。+ 操作符将多个字符串连接在一起。lower()、upper()、find() 和 replace() 等,用于执行常见的字符串操作。下一篇:python input函数用法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站