首页 > 编程语言 > 详细

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

时间:2020-06-15 16:50:57      阅读:36      评论:0      收藏:0      [点我收藏+]

字符串

字符串方法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

 

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

原文:https://www.cnblogs.com/LQZ888/p/13131402.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!