一、设置字符串的格式:精简版

方法1

>>> format = "Hello %s, welcome to %s"
>>> values = ("tom", "shanghai")
>>> format % values
'Hello tom, Welcome to shanghai'

方法2

>>> from string import Template
>>> tmpl = Template("Hello $who, Welcome to $where")
>>> tmpl.substitute(who="tom", where="shanghai")
'Hello tom, Welcome to shanghai'

方法3

#无名称无索引
>>> "{},{} and {}".format("first", "second","third")
'first, second and third'
#有索引
>>> "{1},{0} and {2}".format("second","first","third")
'first, second and third'
#有名字
>>> from math import pi
>>> "{name} is approximately {value:.2f}".format(name="π",value=pi)
'π is approximately 3.14'

二、设置字符串的格式:完整版

1.替换字段名

>>>"{foo}, {}, {}, {bar}".format(5,4,foo=6,bar=9)
'6, 5, 4, 9'
>>>"{foo}, {1}, {0}, {bar}".format(5,4,foo=6,bar=9)
'6, 4, 5, 9'
>>> familyname = ["liu", "zhang"]
>>> "Mr {name[0]}".format(name=familyname)
'Mr liu'

2.基本转换

s、r和a分别使用str、repr和ascii进行转换

>>> print("{pi!s} {pi!r} {pi!a}".format(pi="π"))
π 'π' '\u03c0'

可指定转换为的类型

#转为8进制

>>> "the number is {num:o}".format(num=60)
'the number is 74' #转为百分数
>>> "the number is {num:%}".format(num=60)
'the number is 6000.000000%' #转为小数,用f
>>> "the number is {num:.2f}".format(num=60)
'the number is 60.00' #转为十六进制,用x
>>> "the number is {num:x}".format(num=60)
'the number is 3c' #转为二进制 用b
>>> "the number is {num:b}".format(num=60)
'the number is 111100'

3.宽度、精度和千位分割符

#设置宽度
>>> "{num:10}".format(num=3)
' 3'
>>> "{str:10}".format(str="abc")
'abc '
#设置精度
>>> from math import pi
>>> "Pi day is {pi:.2f}".format(pi=pi)
'Pi day is 3.14'
#设置宽度和精度
>>> from math import pi
>>> "Pi day is {pi:10.2f}".format(pi=pi)
'Pi day is 3.14'
#设置千分位分割符用逗号
>>> "the price of TV is {:,}".format(3689)
'the price of TV is 3,689'

4.符号、对齐和用0填充

#用0填充,宽度保持10位,2位小数
>>> from math import pi
>>> "{:010.2f}".format(pi)
'0000003.14'
#左对齐用<
>>> print('{:<10.2f}'.format(pi))
3.14
#居中用^
>>> print('{:^10.2f}'.format(pi))
3.14
#右对齐用>
>>> print('{:>10.2f}'.format(pi))
3.14
#制定填充字符π
>>> print('{:π^10.2f}'.format(pi))
πππ3.14πππ
#等号=制定填充字符位于符号和数字中间
>>> print('{:=10.2f}'.format(-pi))
- 3.14
>>> print('{:10.2f}'.format(-pi))
-3.14

三、字符串方法

#center,字符串两边添加填充字符
>>> "wolaile".center(10)
' wolaile '
#center,字符串两边添加填充字符,指定字符#
>>> "wolaile".center(10, "#")
'#wolaile##'
>>>
#find方法,在给定的字符串中查找子串,找到返回index
>>> "wolaile".find("ai")
3
#find方法,找不到返回-1
>>> "wolaile".find("aia")
-1
#find方法指定起点和终点,第二个参数起点,第三个参数终点
>>> "wolaile shanghai nihao".find("ha",9)
9
>>> "wolaile shanghai nihao".find("ha",10)
13
>>> "wolaile shanghai nihao".find("ha",10,11)
-1
#join用于合并序列的元素,跟split相反
>>> seq=['1','2','3','4','5']
>>> sep='+'
>>> sep.join(seq)
'1+2+3+4+5'

>>> dirs = '','usr','bin','env'
>>> dirs
('', 'usr', 'bin', 'env')
>>> '/'.join(dirs)
'/usr/bin/env'
#lower用于返回字符串的小写
>>> "WOLAILE".lower()
'wolaile' #title 用于首字符大写(单词分割可能会有问题)
>>> "that's all folks".title()
"That'S All Folks" #capwords也是用于首字符大写
>>> import string
>>> string.capwords("this's a cat")
"This's A Cat"
#replace 替换
>>> "this is a cat".replace("cat", "dog")
'this is a dog' #split 用于分割,与join相反
>>> '/usr/bin/env'.split("/")
['', 'usr', 'bin', 'env'] #strip 删除字符串的开头和结尾的空白,中间的忽略
>>> " biu biu ".strip()
'biu biu'
#strip还可以删除字符串中首尾指定的字符
>>> "###haha # biu $ biu$$$".strip("#$")
'haha # biu $ biu'
#translate 作用类似replace,效率比replace高,使用前需创建转换表
>>> table = str.maketrans("cs","kz")
>>> table
{99: 107, 115: 122}
>>> "this is an incredible test".translate(table)
'thiz iz an inkredible tezt'
 

python教程-(三)使用字符串的更多相关文章

  1. Python第三章-字符串

    第三章  字符串 3.1 基本字符串操作 Python的字符串和元组差不多,是不可以进行改变的,如果想改变值,可以尝试list序列化之后在进行修改. {    website = 'http://ww ...

  2. Python教程(2.4)——字符串

    2.2节讲过,Python中有字符串类型.在Python中,字符串用'或"括起,例如'abc'."qwerty"等都是字符串.注意'和"并不是字符串的内容. A ...

  3. 简明python教程三-----函数

    函数通过def关键字定义.def关键字后跟一个函数的表标识符名称,然后跟一对圆括号. 圆括号之中可以包括一些变量名,该行以冒号结尾.接下来是一块语句,它们是函数体. def sayHello(): p ...

  4. python基础三之字符串

    Python的数据类型 数字(int),如1,2,3,用于计算. 字符串(str),如s = 'zxc',储存少量数据,进行操作. 布尔值(bool),True和False,用于进行判断. 列表(li ...

  5. 写给.NET开发者的Python教程(三):运算符、条件判断和循环语句

    本节会介绍Python中运算符的用法,以及条件判断和循环语句的使用方法. 运算符 运算符包括算术运算符.赋值运算符.比较运算符.逻辑运算符等内容,大部分用法和C#基本一致,下面我们来看一下: 算数运算 ...

  6. python的三种字符串格式化方法

    1.最方便的 print 'hello %s and %s' % ('df', 'another df') 但是,有时候,我们有很多的参数要进行格式化,这个时候,一个一个一一对应就有点麻烦了,于是就有 ...

  7. python 第三章 字符串-例1

    1.字段宽度和精度 >>>'%.*s' % (10,'Gruido') '     Guido' >>>'%.-*s' % (10,'Gruido') 'Guido ...

  8. python教程6-2:字符串标识符

    标识符合法性检查. 1.字母或者下划线开始. 2.后面是字母.下划线或者数字. 3.检查长度大于等于1. 4.可以识别关键字. python35 idcheck.py  idcheck.py impo ...

  9. [Python学习] 模块三.基本字符串

            于Python最重要的数据类型包含字符串.名单.元组和字典.本文重点介绍Python基础知识. 一.字符串基础         字符串指一有序的字符序列集合,用单引號.双引號.三重(单 ...

随机推荐

  1. 使用fiddler抓包模拟器及配置fiddler过滤

    一. 安装fiddler https://www.telerik.com/fiddler 二. 配置fiddler,一下的ip要根据自己电脑情况设置 然后重启Fiddler,一定要重启!!! 三.配置 ...

  2. TP5用join进行查询出来后的循环id都是一样的

    这是因为join将两个表的所有字段都查询,id冲突了,所以需要设置名,或指定选择一个表的id 用field('a.*')

  3. Mysql将其他表中的数据更新到指定表中

    update tb  set tb.字段= (select 字段 from tb1 where tb.字段1 = tb1.字段1); update role set uid = (select ID ...

  4. 使用ELK监控Nginx日志实现接口流量访问统计

    前段时间自己看书学习了一下elasticSearch,后面自己实践了使用elasticSearch.logStash.kibana搭建一个网站接口流量访问统计的监控看板.在这里做一些记录学习. 先看一 ...

  5. ✔PHP文件包含漏洞全面总结

    我的另一篇博客总结的不够全面,但依然有借鉴价值:https://www.cnblogs.com/Zeker62/p/15192610.html 目录 文件包含的定义 文件包含漏洞常见函数 文件包含漏洞 ...

  6. display:flex;下的子元素width无效问题

    因为flex属性默认值为flex:0 1 auto;其中 1 为 flex中的 flex-shrink 属性. 该属性介绍: 一个数字,规定项目将相对于其他灵活的项目进行收缩的量. 根据上述介绍可以理 ...

  7. 理解classpath

    一.什么是classpath classpath,翻译过来就是类路径的意思,它是包含class文件的路径集合,用于指示虚拟机jvm在这些路径下搜索class文件. 类路径可以同时定义多个,多个类路径之 ...

  8. 千位分隔符的JS实现

    $.extend({ //千位分割符 MoneySeparator: function numFormat(num){ if(num==null){ return num; }else { num=n ...

  9. scheduler源码分析——调度流程

    前言 当api-server处理完一个pod的创建请求后,此时可以通过kubectl把pod get出来,但是pod的状态是Pending.在这个Pod能运行在节点上之前,它还需要经过schedule ...

  10. P4544 [USACO10NOV]Buying Feed G

    part 1 暴力 不难发现有一个 $\mathcal O(K^2n)$ 的基础 dp: $$f_{i,j+l}=\min(f_{i,j+l},f_{i-1,j}+(x_i-x_{i-1})\time ...