广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python的字符串方法
  • 671
分享到

Python的字符串方法

字符串方法Python 2023-01-31 00:01:37 671人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

python字符串方法:s.isdigit() -> bool  Return True if all characters in S are digitss.islower() -> bool   Return True if

python字符串方法:


s.isdigit() -> bool  Return True if all characters in S are digits

s.islower() -> bool   Return True if all cased characters in S are lowercase                   

s.isspace() -> bool  Return True if all characters in S are whitespace

s.istitle() -> bool  如果字符串中所有的单词拼写首字母是否为大写,且其他字母为小写则返回 True,否则返回 False.                   

s.isupper() -> bool   如果 string 中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False                  

s.isalpha() -> bool    如果 string 至少有一个字符并且所有字符都是字母则返回 True,否则返回 False                 

s.isalnum() -> bool   如果 string 至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回 False               


s.strip([chars]) -> string or unicode  截掉 string 左边和右边的空格或指定的字符,默认为空格

s.rstrip([chars])-> string or unicode  删除 string 字符串末尾的指定字符(默认为空格).

s.lstrip([chars])  -> string or unicode     用于截掉字符串左边的空格或指定字符               

str = "     this is string example....wow!!!     ";
print str.lstrip();
print str.rstrip();
print str.strip();
str = "88888888this is string example....wow!!!8888888";
print str.lstrip('8');
print str.rstrip('8');
print str.strip('8');



s.split([sep [,maxsplit]]) -> list of strings  以 sep 为分隔符切片 string,如果 maxsplit有指定值,则仅分隔 maxsplit个子字符串

s.rsplit([sep [,maxsplit]]) -> list of strings

s='hello wolrd I love you'
print s.split(' ',2)
print s.rsplit(' ',2)
str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( );
print str.split(' ', 1 );
print str.rsplit( );
print str.rsplit(' ', 1 );


s.splitlines(keepends=False)  -> list of strings        按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。

str1 = 'ab c\n\nde fg\rkl\r\n'
print str1.splitlines();
str2 = 'ab c\n\nde fg\rkl\r\n'
print str2.splitlines(True)



s.index(sub [,start [,end]]) -> int     跟find()方法一样,只不过如果sub不在 string中会报一个异常.

s.rindex(sub [,start [,end]])  -> int  从右边开始.

str1 = "this is string example....wow!!!";
str2 = "exam";
 
print str1.index(str2);
print str1.index(str2, 10);
print str1.index(str2, 40); #抛错

str1 = "this is string example....wow!!!";
str2 = "is";

print str1.rindex(str2);
print str1.index(str2);


s.find(sub [,start [,end]])  -> int        检测 sub 是否包含在 string 中,如果 start 和 end 指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回-1               

s.rfind(sub [,start [,end]])  -> int   右边开始查找.返回字符串最后一次出现的位置(从右向左查询),如果没有匹配项则返回-1。

str = "this is really a string example....wow!!!";
substr = "is";
print str.rfind(substr); #5
print str.rfind(substr, 0, 10); #5
print str.rfind(substr, 10, 0); #-1
print str.find(substr); #2
print str.find(substr, 0, 10); #2
print str.find(substr, 10, 0); #-1


s.ljust(width[, fillchar]) -> string      返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。

s.rjust(width[, fillchar]) -> string

str = "this is string example....wow!!!";
print str.ljust(50, '0');
print str.rjust(50, '0'); #000000000000000000this is string example....wow!!!


s.partition(sep) -> (head, sep, tail)      find()和 split()的结合体,从str出现的第一个位置起,把字符string 分成一个3元素的元组 string_pre_str,str,string_post_str),如果 string 中不包含str 则 string_pre_str== string.

s.rpartition(sep) -> (head, sep, tail)      类似于 partition()函数,不过是从右边开始查找.           


str = "Http://www.w3cschool.cc/"
print str.partition("://") #('http', '://', 'www.w3cschool.cc/')
print str.rpartition("://") #('http', '://', 'www.w3cschool.cc/')
print str.split("://") #['http', 'www.w3cschool.cc/']


s.capitalize() -> string        把字符串的第一个字符大写,其他字母变小写

s = 'a, B'
print s.capitalize() #A, b


s.center(width[, fillchar]) -> string       返回一个原字符串居中,并使用空格填充至长度 width 的新字符串

str = 'runoob'
print str.center(20, '*')
print str.center(20)

   

s.startswith(prefix[, start[, end]]) -> bool  用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查

str = "this is string example....wow!!!";
print str.startswith( 'this' );
print str.startswith( 'is', 2, 4 );
print str.startswith( 'this', 2, 4 );#False


s.endswith(suffix[, start[, end]]) -> bool              用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。可选参数"start"与"end"为检索字符串的开始与结束位置。     

str = "this is string example....wow!!!";
suffix = "wow!!!";
print str.endswith(suffix);
print str.endswith(suffix,20);
suffix = "is";
print str.endswith(suffix, 2, 4);
print str.endswith(suffix, 2, 6); #False


s.count(sub[, start[, end]]) -> int    返回 sub 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 sub出现的次数                   

str = "this is string example....wow!!!";
sub = "i";
print "str.count(sub, 4, 40) : ", str.count(sub, 4, 40)
sub = "wow";
print "str.count(sub) : ", str.count(sub)


s.join(iterable) -> string          join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串              

str = "-";
seq = ["a", "b", "c"]; # 字符串序列
print str.join(seq);


s.decode([encoding[,errors]]) -> object    以encoding指定的编码格式解码string,如果出错默认报一个ValueError的异常,除非 errors指定的是'ignore'或者'replace'   

str = "this is string example....wow!!!";
str = str.encode('base64','strict');
print "Encoded String: " + str;
print "Decoded String: " + str.decode('base64','strict')


s.encode([encoding[,errors]]) -> object      以 encoding 指定的编码格式编码 string,如果出错默认报一个ValueError 的异常,除非 errors 指定的是'ignore'或者'replace'                                       

str = "this is string example....wow!!!";
print "Encoded String: " + str.encode('base64','strict')
print "Encoded String: " + str.encode('UTF-8','strict')


s.swapcase() -> string        翻转 string 中的大小写

s.lower()  -> string              转换 string 中的小写字母为小写           

s.upper()    -> string          转换 string 中的小写字母为大写           

s.title()-> string                 返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写  

str = "this is string example....wow!!!";
print str.title();


s.translate(table [,deletechars]) -> string              据参数table给出的表(包含 256 个字符)转换字符串的字符, 要过滤掉的字符放到 deletechars参数中。

Python2的写法:

import string   # 导入string模块
  
intab = "aeiou"
outtab = "12345"
deltab = "thw"
  
trantab = string.maketrans(intab,outtab) # 创建字符映射转换表
  
test = "this is string example....wow!!!";
  
print test.translate(trantab);
print test.translate(trantab,deltab); # Python2中,删除指定字符在 translate() 方法中


python3的写法:
intab = "aeiou"
outtab = "12345"
deltab = "thw"
  
trantab1 = str.maketrans(intab,outtab) # 创建字符映射转换表
trantab2 = str.maketrans(intab,outtab,deltab) #创建字符映射转换表,并删除指定字符
  
test = "this is string example....wow!!!"
  
print(test.translate(trantab1))
print(test.translate(trantab2))


s.expandtabs([tabsize]) -> string    把字符串中的 tab 符号('\t')转为空格,tab 符号('\t')默认的空格数是 8。     

str = "this is\tstring example....wow!!!";
print "Original string: " + str;
print "Defualt exapanded tab: " +  str.expandtabs(); #默认一个空格替换\t
print "Double exapanded tab: " +  str.expandtabs(16);


s.replace(old, new[, count]) -> string  :返回的替换后的字符串,原来的字符串并不改变

s='hello python,hello world,hello c++,hello java!'
print s.replace('hello','Hello')#将字符串s中的所有'hello'子串,替换成'Hello',返回替换后的字符串,原字符串s不变
print s.replace('hello','Hello',2)#将字符串s中的前2个'hello'子串,替换成'Hello'
print s.replace('wahaha','haha')#要替换的'wahaha'子串不存在,直接返回原字符串


s.fORMat(*args, **kwargs) -> string     

#通过位置格式化
who=('北京','我')
print '{1}去{0}'.format(*who)
#通过关键字格式化
who1={'where':'北京','who':'you'}
print '{who}去{where}'.format(**who1)
print '{:^20}'.format('你好啊') #居中对齐,后面带宽度
print '{:>20}'.format('你好啊') #右对齐,后面带宽度
print '{:<20}'.format('你好啊') #左对齐,后面带宽度
print '{:*<20}'.format('你好啊') #左对齐,后面带宽度,不够就填空
print '{:&>20}'.format('你好啊') #左对齐,后面带宽度,不够就填空
print '{:.1f}'.format(4.234324525254) #精度和类型f
print '{:.4f}'.format(4.1) #精度和类型f
print '{:b}'.format(250) #二进制转换
print '{:o}'.format(250) #八进制转换
print '{:d}'.format(250) #十进制转换
print '{:x}'.format(250) #十六进制转换
print '{:,}'.format(100000000) #千位分隔符,这种情况只针对于数字
print '{:,}'.format(235445.234235) #千位分隔符,这种情况只针对于数字


s.zfill(width) -> string   返回长度为 width 的字符串,原字符串 string 右对齐,如果长度不够前面填充0

s='hello wolrd I love you'
print s.zfill(50)


--结束END--

本文标题: Python的字符串方法

本文链接: https://www.lsjlt.com/news/182758.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Python的字符串方法
    Python字符串方法:s.isdigit() -> bool  Return True if all characters in S are digitss.islower() -> bool   Return True if...
    99+
    2023-01-31
    字符串 方法 Python
  • Python 字符串的方法
    字符串大小写相关 upper()      转换字符串中的所有小写字符为大写。 swapcase()     翻转字符串中的大小写。 lower()       转换字符串中所有大写字符为小写。 capitalize()      把字...
    99+
    2023-01-31
    字符串 方法 Python
  • Python字符串处理的方法
    本文小编为大家详细介绍“Python字符串处理的方法”,内容详细,步骤清晰,细节处理妥当,希望这篇“Python字符串处理的方法”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。 ...
    99+
    2022-10-19
  • python字符串处理方法
    字符和字符串可以用来相加来组合成一个字符串输出;   字符或字符串复制输出。   You can extract a substring from a string by using slice. Format: [start:e...
    99+
    2023-01-31
    字符串 方法 python
  • python字符串常用方法
    目录1、find(sub[,start[,end]])2、count(sub,start,end)3、replace(old,new,count)4、split(sep,maxspl...
    99+
    2022-11-12
  • python用split多字符分割字符串的方法
    python 有内置函数split()分隔字符串,但这个内置函数只能识别单个分隔符。 调用方法如下:  str.split(str="", num=string.count(str)). 其中:  str -- 分隔符,默认为所有的空字符,...
    99+
    2023-09-25
    python 开发语言
  • Python 格式化输出字符串的方法(输出字符串+数字的几种方法)
    目录Python 格式化输出字符串(输出字符串+数字的几种方法)1. 介绍2. 方法2.1 使用占位符%输出2.2 format格式化2.2.1 一般用法2.2.2 进阶用法2.3 ...
    99+
    2023-03-02
    Python 格式化输出字符串 Python 格式化输出
  • python之字符串操作方法
    定义及特性:   以引号(单引号,双引号,三引号)包围且不能修改a= ' \t aBcdE fgFijDlmNopq rSt uTwxy z 123 !@# \t '一、判断字符串,返回bool值:False或Trueprint(a.isi...
    99+
    2023-01-31
    字符串 操作方法 python
  • Python 字符串内置方法(一)
    以下方法只需要知道用法就行了,权当了解,不用硬背,以后需要用到的时候再回来看 说明: 一般方法中前面是is开头的就是判断来的,输出不是True就是False,例如isalpha()方法 capitalize()方法:首字母大写 In [...
    99+
    2023-01-31
    字符串 方法 Python
  • python字符串str.format()方法详解
    一、str.format()方法详解 1.定义和用法 format() 方法格式化指定的值,并将其插入字符串的占位符内。占位符使用大括号 {} 定义,可以使用命名索引 {price}、编号索引{0}、...
    99+
    2023-09-05
    python 开发语言
  • Python字符串的用法
    本篇内容介绍了“Python字符串的用法”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!0. 拼接字符串字符串的拼接操作最常用,我专门为这个话...
    99+
    2023-06-17
  • Python字符串特性及常用字符串方法的简单笔记
    单引号和双引号都能表示字符串。区别在于转义的时候。 如果懒得加转义字符,可以通过在字符串前面加上r。例如: print r'C:somename' 通过在字符串里面添加反斜杠来不换行。 prin...
    99+
    2022-06-04
    字符串 性及 常用
  • javascript字符串替换字符的方法
    这篇文章主要介绍“javascript字符串替换字符的方法”,在日常操作中,相信很多人在javascript字符串替换字符的方法问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”...
    99+
    2022-10-19
  • python中partition分割字符串的方法
    小编给大家分享一下python中partition分割字符串的方法,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!1、说明根据指定的分隔符分割文字符串。如果字串中含...
    99+
    2023-06-15
  • Python对象转JSON字符串的方法
    本文实例讲述了Python对象转JSON字符串的方法。分享给大家供大家参考,具体如下: import json class JSONObject(object): def __init__(self...
    99+
    2022-06-04
    字符串 对象 方法
  • Python 的内置字符串方法小结
    字符串处理是非常常用的技能,但 Python 内置字符串方法太多,常常遗忘,为了便于快速参考,特地依据 Python 3.5.1 给每个内置方法写了示例并进行了归类,便于大家索引。 PS: 可以点击概览内...
    99+
    2022-06-04
    小结 字符串 方法
  • Python字符串替换的3种方法
    Python字符串替换笔记主要展示了如何在Python中替换字符串。Python中有以下几种替换字符串的方法,本文主要介绍前三种。 replace方法(常用)translate方法re.sub方法字符...
    99+
    2023-09-09
    python 开发语言 字符串
  • Python中字符串的方法有哪些
    Python中字符串的方法有很多,下面是一些常用的字符串方法:- `capitalize()`: 将字符串的第一个字符转换为大写,并...
    99+
    2023-08-30
    Python
  • Python入门_浅谈字符串的分片与索引、字符串的方法
    这篇文章主要介绍了字符串的分片与索引、字符串的方法。 字符串的分片与索引: 字符串可以用过string[X]来分片与索引。分片,简言之,就是从字符串总拿出一部分,储存在另一个地方。 看下面这个例子,stri...
    99+
    2022-06-04
    字符串 浅谈 索引
  • JavaScript字符串运算符、字符串和数字相加的方法
    本篇内容介绍了“JavaScript字符串运算符、字符串和数字相加的方法”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能...
    99+
    2022-10-19
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作