首页 > 编程语言 >31个必备的Python字符串方法总结

31个必备的Python字符串方法总结

时间:2023-09-09 15:13:29浏览次数:28  
标签:string Python 31 hello python 字符串 print 必备 methods

 

字符串是Python中基本的数据类型,几乎在每个Python程序中都会使用到它。

 

1、Slicing

slicing切片,按照一定条件从列表或者元组中取出部分元素(比如特定范围、索引、分割值)

s = '   hello   '
s = s[:]
print(s)
#    hello
s = '   hello   '
s = s[3:8]
print(s)
# hello

 

2、strip()

strip()方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。

s = '   hello   '.strip()
print(s)
# hello
s = '###hello###'.strip()
print(s)
# ###hello###

在使用strip()方法时,默认去除空格或换行符,所以#号并没有去除。

可以给strip()方法添加指定字符,如下所示。

s = '###hello###'.strip('#')
print(s)
# hello

此外当指定内容不在头尾处时,并不会被去除。

s = ' \n \t hello\n'.strip('\n')
print(s)
#
#      hello
s = '\n \t hello\n'.strip('\n')
print(s)
#      hello

第一个\n前有个空格,所以只会去取尾部的换行符。

最后strip()方法的参数是剥离其值的所有组合,这个可以看下面这个案例。

s = 'www.baidu.com'.strip('cmow.')
print(s)
# baidu

最外层的首字符和尾字符参数值将从字符串中剥离。字符从前端移除,直到到达一个不包含在字符集中的字符串字符为止。

在尾部也会发生类似的动作。

 

3、lstrip()

移除字符串左侧指定的字符(默认为空格或换行符)或字符序列。

s = '   hello   '.lstrip()
print(s)
# hello

同样的,可以移除左侧所有包含在字符集中的字符串。

s = 'Arthur: three!'.lstrip('Arthur: ')
print(s)
# ee!

 

4、rstrip()

移除字符串右侧指定的字符(默认为空格或换行符)或字符序列。

s = '   hello   '.rstrip()
print(s)
#    hello

 

5、removeprefix()

Python3.9中移除前缀的函数。

# python 3.9
s = 'Arthur: three!'.removeprefix('Arthur: ')
print(s)
# three!

和strip()相比,并不会把字符集中的字符串进行逐个匹配。

 

6、removesuffix()

Python3.9中移除后缀的函数。

s = 'HelloPython'.removesuffix('Python')
print(s)
# Hello

 

7、replace()

把字符串中的内容替换成指定的内容。

s = 'string methods in python'.replace(' ', '-')
print(s)
# string-methods-in-python
s = 'string methods in python'.replace(' ', '')
print(s)
# stringmethodsinpython

 

8、re.sub()

re是正则的表达式,sub是substitute表示替换。

re.sub则是相对复杂点的替换。

import re
s = "string    methods in python"
s2 = s.replace(' ', '-')
print(s2)
# string----methods-in-python
s = "string    methods in python"
s2 = re.sub("\s+", "-", s)
print(s2)
# string-methods-in-python

和replace()做对比,使用re.sub()进行替换操作,确实更高级点。

 

9、split()

对字符串做分隔处理,最终的结果是一个列表。

s = 'string methods in python'.split()
print(s)
# ['string', 'methods', 'in', 'python']

当不指定分隔符时,默认按空格分隔。

s = 'string methods in python'.split(',')
print(s)
# ['string methods in python']

此外,还可以指定字符串的分隔次数。

s = 'string methods in python'.split(' ', maxsplit=1)
print(s)
# ['string', 'methods in python']

 

10、rsplit()

从右侧开始对字符串进行分隔。

s = 'string methods in python'.rsplit(' ', maxsplit=1)
print(s)
# ['string methods in', 'python']

 

11、join()

string.join(seq)。以string作为分隔符,将seq中所有的元素(的字符串表示)合并为一个新的字符串。

list_of_strings = ['string', 'methods', 'in', 'python']
s = '-'.join(list_of_strings)
print(s)
# string-methods-in-python
list_of_strings = ['string', 'methods', 'in', 'python']
s = ' '.join(list_of_strings)
print(s)
# string methods in python

 

12、upper()

将字符串中的字母,全部转换为大写。

s = 'simple is better than complex'.upper()
print(s)
# SIMPLE IS BETTER THAN COMPLEX

 

13、lower()

将字符串中的字母,全部转换为小写。

s = 'SIMPLE IS BETTER THAN COMPLEX'.lower()
print(s)
# simple is better than complex

 

14、capitalize()

将字符串中的首个字母转换为大写。

s = 'simple is better than complex'.capitalize()
print(s)
# Simple is better than complex

 

15、islower()

判断字符串中的所有字母是否都为小写,是则返回True,否则返回False。

print('SIMPLE IS BETTER THAN COMPLEX'.islower()) # False
print('simple is better than complex'.islower()) # True

 

16、isupper()

判断字符串中的所有字母是否都为大写,是则返回True,否则返回False。

print('SIMPLE IS BETTER THAN COMPLEX'.isupper()) # True
print('SIMPLE IS BETTER THAN complex'.isupper()) # False

 

17、isalpha()

如果字符串至少有一个字符并且所有字符都是字母,则返回 True,否则返回 False。

s = 'python'
print(s.isalpha())
# True
s = '123'
print(s.isalpha())
# False
s = 'python123'
print(s.isalpha())
# False
s = 'python-123'
print(s.isalpha())
# False

 

18、isnumeric()

如果字符串中只包含数字字符,则返回 True,否则返回 False。

s = 'python'
print(s.isnumeric())
# False
s = '123'
print(s.isnumeric())
# True
s = 'python123'
print(s.isnumeric())
# False
s = 'python-123'
print(s.isnumeric())
# False

 

19、isalnum()

如果字符串中至少有一个字符并且所有字符都是字母或数字,则返回True,否则返回 False。

s = 'python'
print(s.isalnum())
# True
s = '123'
print(s.isalnum())
# True
s = 'python123'
print(s.isalnum())
# True
s = 'python-123'
print(s.isalnum())
# False

 

20、count()

返回指定内容在字符串中出现的次数。

n = 'hello world'.count('o')
print(n)
# 2
n = 'hello world'.count('oo')
print(n)
# 0

 

21、find()

检测指定内容是否包含在字符串中,如果是返回开始的索引值,否则返回-1。

s = 'Machine Learning'
idx = s.find('a')
print(idx)
print(s[idx:])
# 1
# achine Learning
s = 'Machine Learning'
idx = s.find('aa')
print(idx)
print(s[idx:])
# -1
# g

此外,还可以指定开始的范围。

s = 'Machine Learning'
idx = s.find('a', 2)
print(idx)
print(s[idx:])
# 10
# arning

 

22、rfind()

类似于find()函数,返回字符串最后一次出现的位置,如果没有匹配项则返回 -1。

s = 'Machine Learning'
idx = s.rfind('a')
print(idx)
print(s[idx:])
# 10
# arning

 

23、startswith()

检查字符串是否是以指定内容开头,是则返回 True,否则返回 False。

print('Patrick'.startswith('P'))
# True

 

24、endswith()

检查字符串是否是以指定内容结束,是则返回 True,否则返回 False。

print('Patrick'.endswith('ck'))
# True

 

25、partition()

string.partition(str),有点像find()和split()的结合体。

从str出现的第一个位置起,把字符串string分成一个3 元素的元组(string_pre_str,str,string_post_str),如果string中不包含str则 string_pre_str==string。

s = 'Python is awesome!'
parts = s.partition('is')
print(parts)
# ('Python ', 'is', ' awesome!')
s = 'Python is awesome!'
parts = s.partition('was')
print(parts)
# ('Python is awesome!', '', '')

 

26、center()

返回一个原字符串居中,并使用空格填充至长度width的新字符串。

s = 'Python is awesome!'
s = s.center(30, '-')
print(s)
# ------Python is awesome!------

 

27、ljust()

返回一个原字符串左对齐,并使用空格填充至长度width的新字符串。

s = 'Python is awesome!'
s = s.ljust(30, '-')
print(s)
# Python is awesome!------------

 

28、rjust()

返回一个原字符串右对齐,并使用空格填充至长度width的新字符串。

s = 'Python is awesome!'
s = s.rjust(30, '-')
print(s)
# ------------Python is awesome!

 

29、f-Strings

f-string是格式化字符串的新语法。

与其他格式化方式相比,它们不仅更易读,更简洁,不易出错,而且速度更快!

num = 1
language = 'Python'
s = f'{language} is the number {num} in programming!'
print(s)
# Python is the number 1 in programming!
num = 1
language = 'Python'
s = f'{language} is the number {num*8} in programming!'
print(s)
# Python is the number 8 in programming!

 

30、swapcase()

翻转字符串中的字母大小写。

s = 'HELLO world'
s = s.swapcase()
print(s)
# hello WORLD

 

31、zfill()

string.zfill(width)。

返回长度为width的字符串,原字符串string右对齐,前面填充0。

s = '42'.zfill(5)
print(s)
# 00042
s = '-42'.zfill(5)
print(s)
# -0042
s = '+42'.zfill(5)
print(s)
# +0042

标签:string,Python,31,hello,python,字符串,print,必备,methods
From: https://www.cnblogs.com/wyj497022944/p/17689477.html

相关文章

  • python-55-打包exe执行
    目录前言一、pyinstaller二、实践打包exe1、遇坑1:Pluginalreadyregistered2、遇坑2:OSError句柄无效三、总结前言你是否有这种烦恼?别人在使用你的项目时可能还需要安装各种依赖包?别人在使用你的项目,可能Ta压根都不会安装环境?共用服务机器,偶尔被别人改了依赖包版本,导致运行......
  • Python学习笔记:pandas.Series.str.split分列
    split()方法通过指定分隔符对字符串进行切分,返回分割后的字符串列表  pandas.str.split分列Series.str.split(pat=None,expand=False)  返回分割后的Series ......
  • Python学习 -- 文件内容操作技术详解
    文件操作在编程中是一个常见的任务,Python提供了丰富而灵活的文件操作工具,能够帮助您轻松地读取、写入和处理文件内容。在本篇博客中,我们将深入探讨Python中文件操作的各种技术和方法,包括打开文件、读写文件、移动文件指针、关闭文件等。打开文件在Python中,使用内置的open函......
  • 创建Anaconda虚拟Python环境的方法
      本文介绍在Anaconda环境下,创建、使用与删除Python虚拟环境的方法。  在Python的使用过程中,我们常常由于不同Python版本以及不同第三方库版本的支持情况与相互之间的冲突情况,而需要创建不同的Python虚拟环境;在Anaconda的帮助下,这一步骤就变得十分方便。  首先,我们需要打......
  • python进阶 day08字典数据类型内置方法
    字典数据类型内置方法1.作用对于值添加描述信息使用他2.定义方式用{}以逗号隔开加入键值对:key:valueinfo_dict={'name':'wangdapao','age':18,'height':120,'gender':'female','hobby_list':['dapao','basketball'......
  • Python给你一个字符串,你怎么判断是不是ipv4地址?手写这段代码,并写出测试用例【杭州多测
    ipv4地址的格式:(1~255).(0 ~255).(0 ~255).(0 ~255)1.正则表达式importredefcheck_ip(one_str):compile_ip=re.compile('^(([1-9]|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])$')ifcompile_ip.match(one_str......
  • IDEA 准点下班必备插件推荐!
    InteIIiJIDEA2023.2版本发布了,在2023.2中,官方根据用户的宝贵反馈对新UI做出了大量改进,新UI界面大大减少了干扰,可以让用户更好地专注于代码。但官方激活码的校验规则进行了更新,之前已经成功激活的Idea可能突然无法使用了,给大家准备了激活码:IDEA激活 https://www.kdocs.cn/l/c......
  • python实现输入一个字符串,输出第m个只出现过n次的字符
    功能需求输入一个字符串str,输出第m个只出现过n次的字符功能分析1:定义一个函数,函数传入三个参数,分别是输入的字符串、第m个、n次。2:统计每个字符在字符串中出现的次数,然后按照出现次数进行排序。3:找到第m个只出现n次的字符并输出。程序实现deffind_char(str,m,n):#统......
  • 朴素贝叶斯分类 -python
    算法思想——基于概率的预测贝叶斯决策论是概率框架下实施决策的基本方法。对分类任务来说,在所有相关概率都已知的情况下,贝叶斯决策论考虑如何基于这些概率和误判损失来选择最优的标记类别。理论基础贝叶斯定理这个定理解决了现实生活中经常遇到的问题:已知某条件概......
  • IntelliJ IDEA 必备插件!让的你生产力提升十倍!
    InteIIiJIDEA2023.2版本发布了,在2023.2中,官方根据用户的宝贵反馈对新UI做出了大量改进,新UI界面大大减少了干扰,可以让用户更好地专注于代码。但官方激活码的校验规则进行了更新,之前已经成功激活的Idea可能突然无法使用了,给大家准备了激活码:IDEA激活 https://www.kdocs.cn/l/c......