设为首页 收藏本站
查看: 1042|回复: 0

[经验分享] Python的字符串方法

[复制链接]

尚未签到

发表于 2018-8-8 10:44:43 | 显示全部楼层 |阅读模式
  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       返回一个原字符串居中,并使用空格填充至长度>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   返回长度为>s='hello wolrd I love you'  
print s.zfill(50)

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-548566-1-1.html 上篇帖子: python文件读取 readlines()方法之坑 下篇帖子: Python 自动化运维1-Python安装
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表