# Python 字符串操作示例
# 1. 字符串拼接
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # 输出: Hello World
# 2. 字符串长度
length = len("Hello")
print(length) # 输出: 5
# 3. 字符串索引和切片
s = "Python"
print(s[0]) # 输出: P (第一个字符)
print(s[-1]) # 输出: n (最后一个字符)
print(s[1:4]) # 输出: yth (从索引1到索引3的子字符串)
# 4. 字符串查找
s = "Hello, world!"
print(s.find("world")) # 输出: 7 (找到 "world" 的起始索引)
print(s.find("Python")) # 输出: -1 (未找到,返回 -1)
# 5. 字符串替换
s = "Hello, world!"
new_s = s.replace("world", "Python")
print(new_s) # 输出: Hello, Python!
# 6. 字符串分割
s = "apple,banana,orange"
fruits = s.split(",")
print(fruits) # 输出: ['apple', 'banana', 'orange']
# 7. 字符串去空格
s = " Hello, world! "
trimmed_s = s.strip()
print(trimmed_s) # 输出: Hello, world!
# 8. 字符串大小写转换
s = "hello, world!"
upper_s = s.upper()
lower_s = s.lower()
print(upper_s) # 输出: HELLO, WORLD!
print(lower_s) # 输出: hello, world!
上一篇:python __str__
下一篇:python不换行输出
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站