Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python字符串方法

作者:メ可遇不可求   发布日期:2026-02-13   浏览:103

# 示例代码:Python 字符串方法

# 1. upper() 方法:将字符串中的所有字符转换为大写
s = "hello world"
print(s.upper())  # 输出: HELLO WORLD

# 2. lower() 方法:将字符串中的所有字符转换为小写
s = "HELLO WORLD"
print(s.lower())  # 输出: hello world

# 3. capitalize() 方法:将字符串的第一个字符转换为大写,其余字符转换为小写
s = "hELLO wORLD"
print(s.capitalize())  # 输出: Hello world

# 4. title() 方法:将字符串中每个单词的首字母转换为大写
s = "hello world"
print(s.title())  # 输出: Hello World

# 5. strip() 方法:去除字符串两端的空白字符(包括空格、换行符等)
s = "   hello world   "
print(s.strip())  # 输出: hello world

# 6. replace() 方法:替换字符串中的指定字符
s = "hello world"
print(s.replace("world", "Python"))  # 输出: hello Python

# 7. split() 方法:按照指定分隔符分割字符串,并返回一个列表
s = "hello,world,python"
print(s.split(","))  # 输出: ['hello', 'world', 'python']

# 8. join() 方法:将序列中的元素以指定的字符连接生成一个新的字符串
lst = ["hello", "world", "python"]
print(" ".join(lst))  # 输出: hello world python

# 9. startswith() 和 endswith() 方法:检查字符串是否以指定的前缀或后缀开头或结尾
s = "hello world"
print(s.startswith("hello"))  # 输出: True
print(s.endswith("world"))  # 输出: True

# 10. find() 和 index() 方法:查找子字符串在字符串中的位置
s = "hello world"
print(s.find("world"))  # 输出: 6
print(s.index("world"))  # 输出: 6

# 注意:find() 如果找不到子字符串会返回 -1,而 index() 会抛出 ValueError 异常

上一篇:python 字符串合并

下一篇:python中整除运算符

大家都在看

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

staticmethod在python中有

python 保存json文件

python开发windows应用程序

python中len是什么意思

python 私有函数

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站