# 示例代码:Python字符串处理
# 1. 字符串的创建和基本操作
s = "Hello, World!"
print(s) # 输出: Hello, World!
# 2. 字符串长度
length = len(s)
print(f"字符串长度是: {length}") # 输出: 字符串长度是: 13
# 3. 字符串索引和切片
first_char = s[0] # 获取第一个字符
substring = s[0:5] # 获取从索引0到4的子字符串
print(f"第一个字符是: {first_char}, 子字符串是: {substring}") # 输出: 第一个字符是: H, 子字符串是: Hello
# 4. 字符串拼接
greeting = "Hello"
name = "Alice"
message = greeting + ", " + name + "!"
print(message) # 输出: Hello, Alice!
# 5. 字符串方法
lowercase = s.lower() # 转换为小写
uppercase = s.upper() # 转换为大写
replace_result = s.replace("World", "Python") # 替换子字符串
print(f"小写: {lowercase}, 大写: {uppercase}, 替换后: {replace_result}")
# 输出: 小写: hello, world!, 大写: HELLO, WORLD!, 替换后: Hello, Python!
# 6. 字符串格式化
formatted_string = f"Welcome, {name}!"
print(formatted_string) # 输出: Welcome, Alice!
# 7. 去除空白字符
stripped_string = " extra spaces ".strip()
print(f"去除空白字符后: '{stripped_string}'") # 输出: 去除空白字符后: 'extra spaces'
上一篇:endswith函数python
下一篇:python decorator
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站