python中常用的字符串和使用方法

字符串

字符串方法format,替代字符串用花括号括起来,
"{}, {}, and {}".format("first", “second”, "third"),替换字段没有索引或者名称则按顺序替换,若有索引或名称,就按索引和名称替换。

 

# 无索引按默认顺序替换
txt = "{},{}, and {}"
txt.format("first","second","third")
>>> 'first,second, and third'

# 索引替换
txt = "{1},{2},{0}, and {1}"
txt.format("first","second","third")
>>> 'second,third,first, and second'

# 按名称替换
txt = "{name} is approximately {value: .2f}"
txt.format(value = pi, name = "π")
>>> 'π is approximately  3.14'

 

字符串方法
txt.center(width, "symbol"):居中,width:表示宽度;
txt.ljust(width, "symbol"):居左;
txt.rjust(width, "symbol"):居右;
txt.zfill(width):居右,空位用0填充;
txt.find("xxx", start, end):在字符串中找子串,返回第一个字符的索引,如果没有就返回-1;
join:合并序列

seq = ["1", "2", "3", "4"]
sep = '+'
sep.join(seq)
>>> '1+2+3+4'
  1. txt.lower():返回小写字母;
  2. txt.title():词首字母大写;
  3. txt.replace('old', 'new'):替换;
  4. split:拆除
'1+2+3+4'.split('+')
>>> ["1", "2", "3", "4"]
  1. txt.strip():删除开头和结尾的空白;
  2. translate
from string import maketrans   # 引用 maketrans 函数。
 
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
 
str = "this is string example....wow!!!";
print str.translate(trantab);

>>> 'th3s 3s str3ng 2x1mpl2....w4w!!!'

[resource:](https://www.runoob.com/python/att-string-translate.html)

 

判断是否符合条件,返回布尔值的方法。
isdigit、islower、istitle等等…

 

 

原文链接:https://blog.csdn.net/leeyns/article/details/106169733

 

posted @ 2020-06-15 15:55  逍-遥  阅读(186)  评论(0编辑  收藏  举报
民营企业网B2B