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

方法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. Spring Native实战(畅快体验79毫秒启动springboot应用)

    欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...

  2. 分布式文件系统FastDFS在CentOS7上的安装及与Springboot的整合

    1. 概述 FastDFS 是目前比较流行的分布式文件系统,可以很容易的实现横向扩展.动态扩容.灾备.高可用和负载均衡. FastDFS 的服务分为 tracker 服务 和 storage 服务,  ...

  3. django安装xadmin

    环境:pycharm  django1.11.20  python2.7(根据网络上的资料,自己整理实现) 下载:https://github.com/sshwsfc/xadmin/tree/mast ...

  4. P3507-[POI2010]GRA-The Minima Game【dp,博弈论】

    正题 题目链接:https://www.luogu.com.cn/problem/P3507 题目大意 \(n\)个数,没人轮流取若干个并获得取走的数中最小数的权值,两人的目标都是自己的权值\(-\) ...

  5. YbtOJ#573-后缀表达【二分图匹配】

    正题 题目链接:https://www.ybtoj.com.cn/contest/115/problem/2 题目大意 给出一个包含字母变量和若干种同级操作符的后缀表达式.求一个等价的表达式满足该表达 ...

  6. HashMap扩容和ConcurrentHashMap

    HashMap 存储结构 HashMap是数组+链表+红黑树(1.8)实现的. (1)Node[] table,即哈希桶数组.Node是内部类,实现了Map.Entry接口,本质是键值对. stati ...

  7. react-native移动端设置android闪屏页

    前言 因为app启动时会白屏一段时间,导致让人用起来非常的不舒服,后来了解一下知道这叫做闪屏 于是着手解决这个白屏的问题,换个颜色?不行,不如用一张好看的图片来替换,这样才让人看起来更加舒服. 那么该 ...

  8. Cookie实现是否第一次登陆/显示上次登陆时间

    Cookie实现是否第一次登陆/显示上次登陆时间 最近刚好看到Cookie这方面知识,对Servlet部分知识已经生疏,重新翻出已经遗弃角落的<JavaWeb开发实战经典>,重新温习了Co ...

  9. Go语言核心36讲(Go语言基础知识二)--学习笔记

    02 | 命令源码文件 我们已经知道,环境变量 GOPATH 指向的是一个或多个工作区,每个工作区中都会有以代码包为基本组织形式的源码文件. 这里的源码文件又分为三种,即:命令源码文件.库源码文件和测 ...

  10. Java(22)常用API一

    1 API 1.1 API概述 什么是API ​ API (Application Programming Interface) :应用程序编程接口 java中的API ​ 指的就是 JDK 中提供的 ...