Python字符串小结——截取,运算符,前缀“r”,大小写,搜索,替换,分割

本文深入讲解了Python中字符串的各种操作,包括子字符串访问、运算符使用、大小写转换、搜索与替换、分割等功能,以及如何利用这些功能进行高效的数据处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python不支持单字符类型,单字符也是作为一个字符串使用

 

s="hello world! abc"
s1="hello world!\n abc"
s2=r"hello world!\n abc"


访问子字符串,可以用方括号来截取字符串
print s[0]
print s[1:4]
print s[0:-1]
print s[2:]

h
ell
hello world! ab
llo world! abc

 

字符串运算符
print "h" in s
print "h" not in s

True
False

字符串前缀“r”不识别转义

print s1
print s2

hello world!
 abc
hello world!\n abc


字符串大小写转换
print s.upper()
print s.lower()
print s.capitalize()
print s.title()

HELLO WORLD! ABC
hello world! abc
Hello world! abc
Hello World! Abc

 

字符串搜索 find rfind count __contains__ 
指定起始位置搜索:find('t',start)
指定起始及结束位置搜索:find('t',start,end)
从右边开始查找:rfind('t')
搜索到多少个指定字符串:count('t')
print s.find("abc")
print s.find("abcd")
print s.find("abc",0,5)
print s.rfind("l")
print s.count("l")
print s.__contains__("abc")

13
-1
-1
9
3
True

 

字符串替换
print s.replace("abc", "xyz")
print s.replace("abc", "xyz")

hello world! xyz
hexyzxyzo world! abc

字符串分割
print s.split(" ")

['hello', 'world!', 'abc']

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值