字符串操作

虽然字符串也是一种序列,但是它和元组一样,不可变的。当你想对它修改时,会引发异常。如

>>> strings = "Let's go"
>>> strings[2] = 'B'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

其他的标准的序列操作,都是可以的。

>>> strings[2]
't'

格式化字符串

>>> formats = 'I am %s'
>>> values = 'zhao'
>>> formats % values
'I am zhao'

formats 是格式化的字符串  values 希望被格式化的值,如果格式化的值有多个的话,一般使用元组。

>>> formats = 'My name is %s , I come from %s'
>>> values = 'Zhao','China'
>>> formats % values
'My name is Zhao , I come from China'

注意 使用列表和其他序列代替元组,只会格式化一个值。只有元组和字典格式化多个值。

其中 %s 称为 转换说明符 (conversion specifier)  s 表示格式化字符串 , 关于其他的可以看表 3 - 1

如果格式化字符串中,包含 % ,那么使用 %% 。就不会误认为转换说明符了。

>>> formats = 'My name is %% %s , I come from %s'
>>> formats % values
'My name is % zhao , I come from china'

格式化字符串希望保留小数位数 如

>>> fomats = 'Pi is %.3f'
>>> fomats % pi
'Pi is 3.142'

%.3f  .3 表示保留的浮点数位数 f 表示浮点数

模板字符串

>>> from string import Template
>>> s = Template('$x is $x')
>>> s.substitute(x='111')
'111 is 111'

如果替换是单词的一部分,必须用 中括号 %{x}  扩起来,不扩起来会引发异常

>>> s = Template("${x}ssss $x ${x}fffff")
>>> s.substitute(x='BB')
'BBssss BB BBfffff'

如果插入美元符号 $$

>>> s = Template("${x}ssss $$ $x ${x}fffff")
>>> s.substitute(x='BB')
'BBssss $ BB BBfffff'

除了关键字参数以外,还可以用字典 键值对形式

>>> s = Template("A $thing $run")
>>> d = {}
>>> d['thing'] = 'thingsssss'
>>> d['run'] = 'runnnnn'
>>> s.substitute(d)
'A thingsssss runnnnn'

用 safe_substitute 方法 不会因为缺少值,而报错。

下面这种格式化字符串会报错,元组 需要 括号 扩起来

错误的

>>> '%s %s %s' % 1,2,3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string

正确应该

>>> '%s %s %s' % (1,2,3)
'1 2 3'

详细的转换说明符

(1) %字符:标记开始转换说明符

(2) 转换标志(可选):  -  表示左对齐; + 表示在转换值之前要加上正负号;"" 表示正数之前保留空格 0 表示转换值若位数不够则用9填充。

(3) 最小字段宽带(可选): 转换后的字符串至少具有该值指定宽度。 如果 * ,则宽度会从元组读出。

(4) 点 (.) 后跟精度值 (可选):如果转换的是实数,精度值就表示出现在小数点后的位数。如果转换的是字符串,那么该数字就表示最大字段宽度。如果 * ,则精度会从元组中读出。

示例一  带符号十进制整数

>>> 'Price of eggs:$%d' % 42
'Price of eggs:$42'

>>> from math import pi
>>> 'pi is %i' % pi
'pi is 3'

示例二  不带符号十六进制

>>> 'Hexadecimal price of eggs %X' % 42
'Hexadecimal price of eggs 2A'
>>> 'Hexadecimal price of eggs %x' % 42
'Hexadecimal price of eggs 2a'

示例三  str函数转换对象

>>> 'Using str of %s' % 42L
'Using str of 42'

示例四 repr函数转换对象

>>> 'Using repr of %r' % 42L
'Using repr of 42L'

字符串表示函数 str、repr

str 把值转换合理的字符串形式,以便用户理解。

repr  把值转换Python表达的字符串形式。

>>> str("Let's go!")
"Let's go!"

>>> repr("Let's go!")
'"Let\'s go!"'

示例五  字段宽度 和 精度

字段宽度 20

>>> '%20s' % 'hello world!'
' hello world!'

精度 2

>>> '%.2f' % 10.9373
'10.94'

>>> '%.2s' % 'Hello World!'
'He'

字段宽度 20 精度 2

>>> '%20.2s' % 'Hello World!'
' He'

用 * 号 代替字段宽度 和 精度

>>> '%*.*s' % (10,2,'Hello World!')
' He'

符号、对齐和0填充 针对数字

字段宽度和精度值之前放置一个'标志',标志 有 零、加号、减号和空格。

示例 零

>>> '%010.2f' % pi
'0000003.14'

示例 减 左对齐数值

>>> '%-10.2f' % pi
'3.14 '

示例 加 显示正负数符号

>>> print('%+10.2f' % 3.14) + '\n'+ ('%+10.2f' % -3.14)
+3.14
-3.14

示例 空格 对齐正负数

>>> print('% 10.2f' % 3.14) + '\n'+ ('% 10.2f' % -3.14)
3.14
-3.14

一个比较简单的程序示例

width = input('Please enter width:')

price_width = 10
item_width = width - price_width header_format = '%-*s%*s'
sub_format = '%-*s%*.2f' print '=' * width print header_format % (item_width, 'Item', price_width, 'Price') print '-' * width print sub_format % (item_width, 'Apple', price_width, 2.4)
print sub_format % (item_width, 'Samsung', price_width, 1.4) print '=' * width

字符串方法

函数一 find

>>> text_content = "Let's go go!"
>>> text_content.find('go')
6
>>> text_content.find('go2')
-1
>>> text_content.find('Let')
0

find 函数 第二个和第三个参数 值的 起始点和终止点

>>> text_content.find('go',1,5)
-1

 >>> text_content.find('go',8)
  9

函数二 join

join 连接序列中的每个元素 而且连接的元素,必须是字符串

它是 split 逆方法

>>> __list = [1,2,3,4,5]
>>> __str = '+'
>>> __str.join(__list)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found
>>> __list = ['','','','','']
>>> __str.join(__list)
'1+2+3+4+5'

函数三 lower

lower 把字符串转换为小写字符母

>>> 'How Are You'.lower()
'how are you'

还有一些其他相关的有 translate、islower、capitalize、swapcase、title、istitle、upper、isupper

>>> 'how are you'.title()
'How Are You'

 >>> import string

>>> string.capwords("that's all, folks")
 "That's All, Folks"

函数四 replace

replace 返回某字符串所有匹配项被替换后的字符串。

>>> 'go go go go go is go'.replace('go','egg')
'egg egg egg egg egg is egg'

关联的其他函数  translate、expandtabs

函数五 split

>>> '1+2+3+4+5'.split('+')
['', '', '', '', '']

如果不提供分隔符,程序会把所有(空格、制表符、换行符)作为分隔符。

关联的其他函数  join、rsplit、splitlines

函数六 strip

>>> '   go go go   '.strip()
'go go go'

strip 去除两个(不包括内部)空格字符串。也可以去除指定符号

>>> '1122**   go go go  112222** '.strip('12* ')
'go go go'

其他函数

lstrip   删除字符串左边的指定字符

rstrip  删除字符串右边的指定字符

函数七 translate

translate替换单个字,它优势可以同时进行多个替换,有些时候比replace效率高。

>>> intab = 'a'
>>> outtab = ''
>>> trantab = maketrans(intab,outtab)
>>> str = 'abal'
>>> print str.translate(trantab)
0b0l
maketrans 函数接受两个参数 两个等长的字符串。它返回的是 转换表

其他函数:replace,lower

函数八 upper 大写

>>> 'hello'.upper()
'HELLO'

函数九 capwords 首字母大写

>>> string.capwords('hello words!')
'Hello Words!'

Python 字符串 (3) 持续更新的更多相关文章

  1. LeetCode python实现题解(持续更新)

    目录 LeetCode Python实现算法简介 0001 两数之和 0002 两数相加 0003 无重复字符的最长子串 0004 寻找两个有序数组的中位数 0005 最长回文子串 0006 Z字型变 ...

  2. LeetCode 题目的 Python 实现(持续更新中)

    Python-LeetCode 是一个使用 Python 语言解决 LeetCode 问题的代码库,库有以下几个方面需要注意: 所有题目都是 AC 的: 按照题目顺序,每 50 个放在一个目录下,方便 ...

  3. Python相关工具清单[持续更新]

    SublimeJEDI : awesome Python autocompletion with SublimeText. Awesome Python : A curated list of awe ...

  4. Python 字典 (4) 持续更新

    字典一种用名字来引用值的数据结构,这种数据结构称为 映射(mapping) .字典中的键可以是数字.字符串和元组. 字典 创建和使用 创建 phonebook = {'Aaron':133000000 ...

  5. python笔记(持续更新)

    1.编译python遇到下面的编码问题:     SyntaxError: Non-ASCII character '\xe9' in file E:\projects\learn.py on lin ...

  6. python tips(持续更新中)

    python tips 可变对象与不可变对象 在python中,可变对象有数值类型(int,float),字符串(str),元组(tuple),可变对象有列表(list),字典(dict),集合(se ...

  7. Python小练习(持续更新....)

    最近一直在学习python,这些小练习有些是书上的,有些是别人博客上的! # 1.题目1# 给一个字符串,统计其中的数字.字母和其他类型字符的个数:# 比如输入“124mid-=”,输出:数字=3,字 ...

  8. python内置模块笔记(持续更新)

    常用函数name = '{wh}my \t name is {name},age is {age}.' print(name.capitalize()) # 字符串的开头字母大写 print(name ...

  9. python tips(持续更新)

    1. 引用上一层目录 import syssys.path.append('..')import xx 2. python json JSON是一种轻量级的数据交换格式.可以解决数据库中文存储问题,对 ...

随机推荐

  1. Redis内存分析工具—redis-rdb-tools (转载http://www.voidcn.com/article/p-axfdqxmd-bro.html)

    redis-rdb-tools是由Python写的用来分析Redis的rdb快照文件用的工具,它可以把rdb快照文件生成json文件或者生成报表用来分析Redis的使用详情.使用标准的diff工具比较 ...

  2. 学习笔记:CentOS7学习之十八:Linux系统启动原理及故障排除

    目录 学习笔记:CentOS7学习之十八:Linux系统启动原理及故障排除 18.1 centos6系统启动过程及相关配置文件 18.1.1 centos6系统启动过程 18.1.2 centos6启 ...

  3. 【持续更新】一个简洁、易用的美赛 LaTeX 模板: easyMCM

    目录 1 当前美赛模板通行情况的概述 2 EasyMCM 宏包说明 2.1 与 mcmthesis 的关系之说明 2.2 easymcm宏包的简介 2.3 美赛模板下载地址 3 README 摘录 3 ...

  4. 宝塔面板liunx开启ssl域名后无法访问解决方法

    不打开宝塔面板的ssl会不安全,打开了就会提示ssl证书不能使用的错误 如下所示: 您的连接不是私密连接 攻击者可能会试图从 你的ip 窃取您的信息(例如:密码.通讯内容或信用卡信息).了解详情 NE ...

  5. Python基础 第三章 使用字符串(1)精简版

    所有标准序列操作(索引,切片,乘法,成员资格检查,长度,最小值,最大值)都适于字符串. 但,字符串是不可变得,故所有得元素赋值和切片赋值都是非法的. 1. %s 转换说明符 设置字符串格式 %左边指定 ...

  6. opencv实现人脸识别(五) 运用tkinter进行GUI绘制 整合人脸识别模块

    因为之前学习过tkinter库,所以在学习了人脸识别模块的编写后, 打算绘制一个简单的GUI来应用人脸识别功能. 主界面如下所示: 签到打开在点开后直接进行人脸识别,如果成功则自动关闭视频窗口. 录入 ...

  7. DeepMind提出新型超参数最优化方法:性能超越手动调参和贝叶斯优化

    DeepMind提出新型超参数最优化方法:性能超越手动调参和贝叶斯优化 2017年11月29日 06:40:37 机器之心V 阅读数 2183   版权声明:本文为博主原创文章,遵循CC 4.0 BY ...

  8. 简单分析BeanPostProcessor

    1. 什么是BeanPostProcessorBeanPostProcessor是一个接口,有两个方法,分别是:Object postProcessBeforeInitialization(Objec ...

  9. [http]HTTP状态码含义

    HTTP状态码 当浏览者访问一个网页时,浏览者的浏览器会向网页所在服务器发出请求.当浏览器接收并显示网页前,此网页所在的服务器会返回一个包含HTTP状态码的信息头(server header)用以响应 ...

  10. Python取值的灵活性用法

    samp_string = "Whatever you are, be a good one." for i in samp_string: print(i) ,len(samp_ ...