python字符串(一):拼接、查找、分割、替换

1.字符串定义
字符串:以双引号或单引号包围的数据
2.字符串的拼接
练习:

a = 'hello'
b = 'world'
c = a + b
print(c)
运行结果:helloworld

3.特殊字符

\ \反斜杠符号
\ ’单引号
\ "双引号
\a响铃
\b退格
\000
\n换行
\v纵向制表符
\t横向制表符
\r回车
\f换页

4.字符串格式化

%s字符串占位符
%d数字占位符
%f浮点型数字占位符
%2f控制浮点型数字占位符

练习:

print('my name is %s'%('ming'))
结果:my name is ming

5.字符串的查找方法

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

6.字符串的分割

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']

7.字符串的替换

replace从左到右替换指定元素,可以指定替换个数,默认全部替换

练习replace

test = 'hello world'
print (test)
print(test.replace('o','x'))
运行结果:hello world
        hellx wxrld
  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python字符串处理是指对字符串进行各种操作和处理的技术。Python提供了丰富的字符串处理方法和函数,可以方便地进行字符串拼接、切片、查找替换等操作。 以下是一些常用的Python字符串处理方法和函数: 1. 字符串拼接:使用"+"运算符可以将两个字符串拼接在一起,例如:`str1 + str2`。 2. 字符串切片:可以通过索引来获取字符串中的部分内容。例如,`str[1:5]`表示获取从索引1到索引4的子字符串。 3. 字符串长度:使用`len()`函数可以获取字符串的长度,例如:`len(str)`。 4. 字符串查找:可以使用`find()`、`index()`等方法来查找字符串中某个子串的位置。例如,`str.find(sub_str)`返回子串在字符串中第一次出现的位置。 5. 字符串替换:使用`replace()`方法可以将字符串中的某个子串替换为另一个子串。例如,`str.replace(old_str, new_str)`将字符串中的old_str替换为new_str。 6. 字符串分割:使用`split()`方法可以将字符串按照指定的分隔符进行分割,返回一个列表。例如,`str.split(separator)`将字符串按照separator进行分割。 7. 字符串大小写转换:使用`lower()`、`upper()`等方法可以将字符串转换为小写或大写形式。例如,`str.lower()`将字符串转换为小写形。 8. 字符串格式化:使用`format()`方法可以将变量的值插入到字符串中的占位符位置。例如,`"Hello, {}!".format(name)`将name的值插入到字符串中的占位符位置。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值