python字符串常用方法整理

参考教程:https://www.w3school.com.cn/python/python_strings.asp
https://www.runoob.com/python3/python3-string.html
注意: 在jupyter 中,可以在方法名后面打一个问号,然后页面下方会显示这个方法的用法和参数介绍。

目录

      • 一、摘要
      • 二、常用的18个方法
        • 1.captialize()
        • 2.center()
        • 3.count()
        • 4.endswith()
        • 5.startswith()
        • 6.find()
        • 7.upper()
        • 8.lower() 把所有字母小写
        • 9.istitle()
        • 10 isupper()
        • 11.islower()
        • 12.strip()
        • 13.rstrip()
        • 14.lstrip()
        • 15.swapcase()
        • 16.join()方法
        • 17.split()
        • 18.replace()
      • 参考文档

一、摘要

在学习数据处理时,对于字符串的处理是一大重要任务。了解python库中封装好的一些函数,可以让字符串处理事半功倍。现将字符串对象常用的18个方法记录如下。内容参考自菜鸟教程和W3school。

二、常用的18个方法

1.captialize()

capitalize() 让字符串的首字母大写 , 其他字母变小写

str = "hello world" 
str = str.capitalize() 
print(str) 
# 结果为"Hello world" 
2.center()

center() 方法将使用指定的字符(默认为空格)作为填充字符使字符串居中对齐。

参数 描述
length 必需。所返回字符串的长度。
character 可选。填补两侧缺失空间的字符。默认是 " "(空格)。

例子:

str = "hello world" 
str = str.center(20) 
print(str) 
# 结果为   '    hello world     ' 
str2 =str.center(20,"+") 
# 结果为 '++++hello world+++++' 
3.count()

str.count() 用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。

参数
描述 sub
搜索的子字符串 start 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。

end 可选。整数。结束检索的位置。默认是字符串的结尾。 例子:

txt = "I love apples, apple are my favorite fruit" 
x = txt.count("apple", 10, 24) 
print(x) 
# 结果为   1 
4.endswith()

str.endswith()如果字符串以指定值结尾,则 endswith() 方法返回 True,否则返回 False。

参数 描述

你可能感兴趣的:(python学习,python,字符串)