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

python 字符串操作

作者:寂寞味道   发布日期:2025-09-17   浏览:90

# 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不换行输出

大家都在看

python时间格式

python读取文件路径

staticmethod在python中有

python开发windows应用程序

python中len是什么意思

python ord和chr

python中的yield

python自定义异常

python判断路径是否存在

python list.pop

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

Laravel 中文站