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

方法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. js判断移动端跳转

    <script type="text/javascript">if(/AppleWebKit.*Mobile/i.test(navigator.userAgent) | ...

  2. Jmeter扩展组件开发(6) - 将响应结果数据显示到查看结果树中

    CODE //用来存储响应数据,目的是将响应结果放到查看结果树当中private String resultData;/** 这个方法就是实现你具体功能逻辑的方法* @param javaSample ...

  3. PHP 合并2个链表

    输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则. <?php class ListNode{ var $val; var $next = NULL; ...

  4. javascript base64 encode decode 支持中文

    * 字符编码 ** 一定要知道数据的字符编码 ** 使用utf-8字符编码存储数据 ** 使用utf-8字符编码输出数据 * Crypto.js 支持中文 Base64编码说明 Base64编码要求把 ...

  5. P5782-[POI2001]和平委员会【2-SAT】

    正题 题目链接:https://www.luogu.com.cn/problem/P5782 题目大意 \(n\)对人,每对之间恰好有一个人出席.\(m\)对仇恨关系表示两个人不能同时出席. 求是否有 ...

  6. P4884-多少个1?【BSGS】

    正题 题目链接:https://www.luogu.com.cn/problem/P4884 题目大意 求一个最小的\(n\)使得\(n\)个连续的\(1\)其在模\(m\)意义下等于\(k\). \ ...

  7. 深入浅出WPF-11.Template(模板)02

    模板 DataTemplate和ControlTemplate的关系 通过上面的内容,控件只是一个数据和行为的载体,是一个抽象的概念,至于它长什么样子,或者它的数据是怎么展示的,都是由模板生成的.决定 ...

  8. NVIDIA驱动安装

    在一次重启之后,NVIDIA显卡突然驱动坏了.实验室同学推测可能是有人安装了caffe,导致驱动被升级了.不论如何,需要重装驱动. 我的开发环境:Ubuntu 16.04 + GeForce GTX ...

  9. Kubernetes集群(RKE)安装ArgoCD排坑

    Photo by Pixabay from Pexels Argo CD是一个声明式的,基于Kubernetes的GitOps持续交付工具.更多的细节参考 ArgoCD官网 的说明,这里记录了一些实践 ...

  10. 浅析 Java 内存模型

    文章转载于 飞天小牛肉 的 <「跬步千里」详解 Java 内存模型与原子性.可见性.有序性>.<JMM 最最最核心的概念:Happens-before 原则> 1. 为什么要学 ...