python教程-(三)使用字符串
一、设置字符串的格式:精简版
方法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教程-(三)使用字符串的更多相关文章
- Python第三章-字符串
第三章 字符串 3.1 基本字符串操作 Python的字符串和元组差不多,是不可以进行改变的,如果想改变值,可以尝试list序列化之后在进行修改. { website = 'http://ww ...
- Python教程(2.4)——字符串
2.2节讲过,Python中有字符串类型.在Python中,字符串用'或"括起,例如'abc'."qwerty"等都是字符串.注意'和"并不是字符串的内容. A ...
- 简明python教程三-----函数
函数通过def关键字定义.def关键字后跟一个函数的表标识符名称,然后跟一对圆括号. 圆括号之中可以包括一些变量名,该行以冒号结尾.接下来是一块语句,它们是函数体. def sayHello(): p ...
- python基础三之字符串
Python的数据类型 数字(int),如1,2,3,用于计算. 字符串(str),如s = 'zxc',储存少量数据,进行操作. 布尔值(bool),True和False,用于进行判断. 列表(li ...
- 写给.NET开发者的Python教程(三):运算符、条件判断和循环语句
本节会介绍Python中运算符的用法,以及条件判断和循环语句的使用方法. 运算符 运算符包括算术运算符.赋值运算符.比较运算符.逻辑运算符等内容,大部分用法和C#基本一致,下面我们来看一下: 算数运算 ...
- python的三种字符串格式化方法
1.最方便的 print 'hello %s and %s' % ('df', 'another df') 但是,有时候,我们有很多的参数要进行格式化,这个时候,一个一个一一对应就有点麻烦了,于是就有 ...
- python 第三章 字符串-例1
1.字段宽度和精度 >>>'%.*s' % (10,'Gruido') ' Guido' >>>'%.-*s' % (10,'Gruido') 'Guido ...
- python教程6-2:字符串标识符
标识符合法性检查. 1.字母或者下划线开始. 2.后面是字母.下划线或者数字. 3.检查长度大于等于1. 4.可以识别关键字. python35 idcheck.py idcheck.py impo ...
- [Python学习] 模块三.基本字符串
于Python最重要的数据类型包含字符串.名单.元组和字典.本文重点介绍Python基础知识. 一.字符串基础 字符串指一有序的字符序列集合,用单引號.双引號.三重(单 ...
随机推荐
- Java定时任务Quartz
第一步:pom文件中添加依赖包 第二步:创建xml文件,名称为:spring-scheduler 路径如下图: 第三步:spring-scheduler配置详情 <!--创建任务--> & ...
- 对象赋值在PHP中到底是不是引用?
之前的文章中,我们说过变量赋值的问题,其中有一个问题是对象在进行变量赋值的时候,直接就是引用赋值.那么到底真实情况是怎样呢? 之前变量赋值的文章 PHP的变量赋值 对象引用测试 在继续深入的学习PHP ...
- contos 安装 nginx
参考链接https://blog.csdn.net/u011159417/article/details/80081992 https://blog.csdn.net/wangxy_job/artic ...
- turtle setup和screensize
关于setup有明确的定义,它包括4个参数width,height,startx,starty, setup定义窗体的大小和相对位置,并隐含定义了画布的位置,缺省是居中占整个屏幕的一半[setup() ...
- python OSError: [Errno 22] Invalid argument: '\u202aF://text
windows10 python3 读文件的时候报的错误 原因不明时好时坏很头疼但又没办法不知道怎么解决,网上的说法都不能解决,
- 数值计算:粒子群优化算法(PSO)
PSO 最近需要用上一点最优化相关的理论,特地去查了些PSO算法相关资料,在此记录下学习笔记,附上程序代码.基础知识参考知乎大佬文章,写得很棒! 传送门 背景 起源:1995年,受到鸟群觅食行为的规律 ...
- 从源码解析Electron的安装为什么这么慢
前言 Electron作为一款跨平台的桌面应用端解决方案已经风靡全球.作为开发者,我们几乎不用关心与操作系统的交互,直接通过Web前端技术与Electron提供的API就可以完成桌面应用端的开发. 然 ...
- 一文读懂 Serverless,将配置化思想复用到平台系统中
作者 | 春哥大魔王 来源 | Serverless 公众号 写在前面 在 SaaS 领域 Salesforce 是佼佼者,其 CRM 的概念已经扩展到了 Marketing.Sales.Servic ...
- 从零入门 Serverless | SAE 场景下,应用流量的负载均衡及路由策略配置实践
作者 | 落语 阿里云云原生技术团队 本文整理自<Serverless 技术公开课>,关注"Serverless"公众号,回复"入门",即可获取 S ...
- 随机生成文章的AI(C++)
#include <iostream> #include <cstdlib> #include <ctime> #include <fstream> u ...