Python 【字符串】 经典范例 :20 个使用方法与技巧

Python “字符串” 经典范例 :20 个使用方法与技巧

以下是 Python 中字符串的 20 个经典使用实例,涵盖了常见的字符串操作和应用场景:


1. 字符串反转

将字符串反转是经典的面试题之一,可以使用切片轻松实现。

s = "hello"
reversed_s = s[::-1]
print(reversed_s)  # 输出 "olleh"

2. 检查回文字符串

回文字符串是指正读和反读都相同的字符串(如 “madam”)。

def is_palindrome(s):
    return s == s[::-1]

print(is_palindrome("madam"))  # 输出 True
print(is_palindrome("hello"))  # 输出 False

3. 统计字符出现次数

统计字符串中某个字符或子字符串的出现次数。

s = "hello world"
count = s.count("l")
print(count)  # 输出 3

4. 字符串分割与连接

将字符串按特定分隔符分割,或将列表中的字符串连接成一个字符串。

# 分割
s = "apple,banana,orange"
fruits = s.split(",")
print(fruits)  # 输出 ['apple', 'banana', 'orange']

# 连接
new_s = "-".join(fruits)
print(new_s)  # 输出 "apple-banana-orange"

5. 字符串格式化

使用 f-stringformat() 方法动态生成字符串。

name = "Alice"
age = 25
# 使用 f-string
print(f"My name is {
     name
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值