# Python字符串函数示例代码
# 1. len() 函数:返回字符串的长度
s = "Hello, World!"
length = len(s)
print(f"字符串 '{s}' 的长度是: {length}") # 输出: 字符串 'Hello, World!' 的长度是: 13
# 2. lower() 方法:将字符串中的所有字符转换为小写
lowercase_s = s.lower()
print(f"转换为小写后的字符串是: {lowercase_s}") # 输出: 转换为小写后的字符串是: hello, world!
# 3. upper() 方法:将字符串中的所有字符转换为大写
uppercase_s = s.upper()
print(f"转换为大写后的字符串是: {uppercase_s}") # 输出: 转换为大写后的字符串是: HELLO, WORLD!
# 4. strip() 方法:去除字符串两端的空白字符(包括空格、制表符和换行符)
stripped_s = " Hello, World! ".strip()
print(f"去除两端空白后的字符串是: '{stripped_s}'") # 输出: 去除两端空白后的字符串是: 'Hello, World!'
# 5. replace() 方法:替换字符串中的指定子字符串
replaced_s = s.replace("World", "Python")
print(f"替换后的字符串是: {replaced_s}") # 输出: 替换后的字符串是: Hello, Python!
# 6. split() 方法:根据指定分隔符将字符串分割成列表
split_s = s.split(", ")
print(f"分割后的列表是: {split_s}") # 输出: 分割后的列表是: ['Hello', 'World!']
# 7. join() 方法:将列表中的元素用指定字符连接成一个新的字符串
joined_s = ", ".join(["Hello", "Python"])
print(f"连接后的字符串是: {joined_s}") # 输出: 连接后的字符串是: Hello, Python
# 8. startswith() 方法:检查字符串是否以指定前缀开头
startswith_result = s.startswith("Hello")
print(f"字符串是否以 'Hello' 开头: {startswith_result}") # 输出: 字符串是否以 'Hello' 开头: True
# 9. endswith() 方法:检查字符串是否以指定后缀结尾
endswith_result = s.endswith("!")
print(f"字符串是否以 '!' 结尾: {endswith_result}") # 输出: 字符串是否以 '!' 结尾: True
# 10. find() 方法:查找子字符串首次出现的位置,如果不存在则返回 -1
find_result = s.find("World")
print(f"'World' 首次出现的位置是: {find_result}") # 输出: 'World' 首次出现的位置是: 7
# 11. count() 方法:计算子字符串在字符串中出现的次数
count_result = s.count("o")
print(f"'o' 在字符串中出现的次数是: {count_result}") # 输出: 'o' 在字符串中出现的次数是: 2
上一篇:python中tuple
下一篇:python 数组拼接
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站