python字符串拼接、查找、分割、替换

本文介绍了Python中字符串的基本操作,包括使用加号进行字符串拼接,通过count、find、rfind、index和rindex进行查找,运用partition和rpartition进行分割,以及使用replace实现字符串替换。通过实例展示了每个方法的功能和用法。

1.字符串定义

字符串:以双引号或单引号包围的数据

2.字符串的拼接

练习:

a = 'hello'

b = 'world'

c = a + b

print(c)

运行结果:helloworld

3.字符串的查找方法

count

计数功能,返回自定字符在字符串中的个数

find

查找,返回从左第一个指定字符的索引,找不到返回-1

rfind

查找,返回从右第一个指定字符的索引,找不到返回-1

index

查找,返回从左附一个指定字符的索引,找不到报错

rindex

查找,返回从右第一个指定字符的索引,找不到报错

Count

 

test = 'hello world'

print(test.count('o'))

运行结果:2

 

Find

 

test = 'hello world'

print(test.find('world'))

运行结果:6

 

test = 'hello world'

print(test.find('word'))

运行结果:-1

 

rfind

 

test = 'hello world'

print(test.rfind('world'))

运行结果:6

 

test = 'hello world'

print(test.rfind('word'))

运行结果:-1

 

Index

 

test = 'hello world'

print(test.index ('o'))

运行结果:4

 

test = 'hello world'

print(test.index ('q'))

运行结果:ValueError: substring not found

 

Rindex

 

test = 'hello world'

print(test.rindex ('o'))

运行结果:7

4.字符串的分割

partition

把字符串从指定位置分成三部分,从左开始 的第一个字符

rpartition

类似partition,从右开始

splitlines

识别每行的\n并合并且分割输出

 

Partition

 

test = 'hello world'

print(test.partition('o'))

运行结果:('hell', 'o', ' world')

 

rpartition

 

test = 'hello world'

print(test.rpartition('o'))

运行结果:('hello w', 'o', 'rld')

 

Splitlines

 

test = 'hello\nworld'

print (test)

print(test.splitlines())

运行结果:hello

        world

       ['hello', 'world']

5.字符串的替换

replace

 

test = 'hello world'

print (test)

print(test.replace('o','x'))

运行结果:hello world

        hellx wxrld

作者:QinL

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值