python字符串常用方法

作者:Silent丿丶黑羽 时间:2023-05-29 13:54:15 

1、find(sub[, start[, end]])

在索引startend之间查找字符串sub
找到,则返回最左端的索引值,未找到,则返回-1
startend都可省略,省略start说明从字符串开头找
省略end说明查找到字符串结尾,全部省略则查找全部字符串


source_str = "There is a string accessing example"
print(source_str.find('r'))
>>> 3

2、count(sub, start, end)

返回字符串substartend之间出现的次数


source_str = "There is a string accessing example"
print(source_str.count('e'))
>>> 5

3、replace(old, new, count)

old代表需要替换的字符,new代表将要替代的字符,count代表替换的次数(省略则表示全部替换)


source_str = "There is a string accessing example"
print(source_str.replace('i', 'I', 1))
>>> There Is a string accessing example # 把小写的i替换成了大写的I

4、split(sep, maxsplit)

sep为分隔符切片,如果maxsplit有指定值,则仅分割maxsplit个字符串
分割后原来的str类型将转换成list类型


source_str = "There is a string accessing example"
print(source_str.split(' ', 3))
>>> ['There', 'is', 'a', 'string accessing example'] # 这里指定maxsplit=3,代表只分割前3个

5、startswith(prefix, start, end)

判断字符串是否是以prefix开头,startend代表从哪个下标开始,哪个下标结束


source_str = "There is a string accessing example"
print(source_str.startswith('There', 0, 9))
>>> True

6、endswith(suffix, start, end)

判断字符串是否以suffix结束,如果是返回True,否则返回False


source_str = "There is a string accessing example"
print(source_str.endswith('example'))
>>> True

7、lower

将所有大写字符转换成小写

8、upper

将所有小写字符转换成大写 

9、join

将列表拼接成字符串


list1 = ['ab', 'cd', 'ef']
print(" ".join(list1))
>>> ab cd ef

10、切片反转


list2 = "hello"
print(list2[::-1])
>>> olleh

来源:https://www.cnblogs.com/jiakecong/p/14438571.html

标签:python,字符串,方法
0
投稿

猜你喜欢

  • 浅谈javascript 函数表达式和函数声明的区别

    2024-04-27 15:19:39
  • Python使用Django实现博客系统完整版

    2021-02-10 14:43:48
  • 使用Python OpenCV为CNN增加图像样本的实现

    2023-10-13 02:51:31
  • XPath详解,总结

    2009-04-17 14:09:00
  • 如何使用Iframe实现本页提交?

    2010-06-05 12:36:00
  • 使用PHP 5.0创建图形的巧妙方法

    2023-10-27 00:59:07
  • Python实战之实现获取动态图表

    2023-10-31 14:03:34
  • python中读入二维csv格式的表格方法详解(以元组/列表形式表示)

    2023-04-19 06:39:39
  • Python代码打开本地.mp4格式文件的方法

    2021-08-27 21:43:04
  • Go获取与设置环境变量的方法详解

    2023-06-21 04:35:10
  • jquery $(document).ready() 与window.onload的区别

    2024-04-19 10:23:59
  • JavaScript图片放大镜效果

    2009-10-19 22:15:00
  • django 前端页面如何实现显示前N条数据

    2023-06-07 10:50:33
  • PHP set_time_limit(0)长连接的实现分析

    2023-11-06 11:46:20
  • python中ThreadPoolExecutor线程池和ProcessPoolExecutor进程池

    2022-08-28 08:26:45
  • 使用Python进行数独求解详解(二)

    2023-02-25 22:33:41
  • 基于python使MUI登录页面的美化

    2023-10-23 16:28:03
  • Python中Subprocess的不同函数解析

    2022-03-10 05:23:00
  • jupyternotebook 撤销删除的操作方式

    2021-04-06 22:12:01
  • Windows2003 IIS+PHP+MySQL配置

    2007-06-15 15:15:00
  • asp之家 网络编程 m.aspxhome.com