3.1 基本字符串操作
Python的字符串和元组差不多,是不可以进行改变的,如果想改变值,可以尝试list序列化之后在进行修改。
{
website = 'http://www.Python.org';
website = [-3:] = 'com';
上面操作违法。
}
3.2 字符串格式化:精简版
字符串格式化使用字符串格式化操作符(这个名字还是很恰当的)即%来实现。
基本用法例子
1.
>>> format = "Hello, %s. %s enough for ya?";
>>> values = ('world' ,'Hot');
>>> print (format % values);
Hello, world. Hot enough for ya?
2.
>>> format = "Pi with three decimals: %.3f";
>>> from math import pi
>>> print(format % pi)
Pi with three decimals: 3.142
3.模板字符串
<基本用法>
>>> from string import Template;
>>> s = Template('$x. glorious $x!');
>>> s.substitute(x='slurm')
'slurm. glorious slurm!'
<模板字符串如果和别的单词一起,那么要{x}区分>
>>> s = Template("It's ${x}tastic!")
>>> s.substitute(x='slurm')
"It's slurmtastic!"
>>>
<显示美元字符用两个$>
>>> s=Template("Make $$ selling $x!");
>>> s.substitute(x='slurm')
'Make $ selling slurm!'
<除了关键字参数之外,还可以使用字典变量提供值/名称对>
>>> s = Template('A $thing must never $action.');
>>> d = {}
>>> d['thing'] = 'gentleman'
>>> d['action'] = 'show his socks'
>>> s.substitute(d)
'A gentleman must never show his socks.'
<safe_substitute 在查找不到的时候不会报错>
>>> s = Template('A $x');
>>> s.substitute(a='x') 这个会报错,因为查找不到
>>> s.safe_substitute(a='x') 不会报错,并且输出下面值
'A $x'
3.3 字符串格式化:完整版
格式化操作符的右操作数可以是任何东西,如果是元组或者映射类型(如字典)那么字符串格式化讲会有所不同。
注意:
如果转换表达式一部分是元组,那么必须将它用括号括起来,以避免出错。
{
Ok
>>> '%s plus %s equals %s' % (1 ,1 ,2)
'1 plus 1 equals 2'
Error
>>> '%s plus %s equals %s' % 1,1,2
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>'%s plus %s equals %s' % 1,1,2
TypeError: not enough arguments for format string
>>>
}
基本转换说明符-(以下描述循序至关重要(就是使用顺序))
(1)%字符:标记转换说明符的开始。
(2)转换标志(可选): -表示左对齐;
+表示在转换值之前要加上正负号
“” 正数之前保留空格
0 0填充
(3) 最小字段宽度(可选):转换后的字符串至少应该具有该指定值的宽度。
如果是*,则宽度会从值元组中读取。
(4)点(.) 后跟随精度值(可选):如果转换的是实数,精度值就表示出现在小数点后的位数。如果转换的是字符串,那么该数字就表示最大字段宽度。如果是*,那么精度将会从元组中读出。
(5)转换类型
d,i 带符号的十进制整数
o 不带符号的八进制
u 不带符号的十进制
x,X 十六进制
e,E 科学计数法
f,F 十进制浮点型
g,G
C 单字符
r 字符串(使用repr转换任意Python对象)
s 字符串(使用str转换任意Ptthon对象)
3.3.1简单转换
>>> 'Price of eggs: $%d' %42
'Price of eggs: $42'
>>> 'Price of eggs: $%d' %42
'Price of eggs: $42'
>>> 'Hexadecimal price of eggs:%x' %42
'Hexadecimal price of eggs:2a'
>>> from math import pi
>>> 'Pi: %f...' %pi
'Pi: 3.141593...'
>>> 'Very inexact estimate of pi: %i' %pi
'Very inexact estimate of pi: 3'
>>> 'Using str: %s' % 42L
SyntaxError: invalid syntax (我用的3.5 高版本里买没有显示L了)
>>> 'Using str: %s' % 42
'Using str: 42'
>>> 'Using repr: %r' %42
'Using repr: 42'
>>>
3.3.2 字段宽度和精度
>>> '%10f' %pi'
3.141593'
>>> '%10.2f' %pi' 3.14'
>>> '%.2f' %pi
'3.14'
>>> '%.2s' %pi
'3.'
>>> '%.5s' % 'Guido van Rossum'
'Guido'
<长度可以用*代替,然后在元组里给出>
>>> '%.*s' %(5,'Guido van Rossum')
'Guido'
3.3.3 符号,对齐和0填充
<0填充>
>>> '%010.2f' %pi
'0000003.14'
<左对齐>
>>> '%-10.2f' %pi
'3.14 '
<空格填充>
>>> print(('% 5d' %10) + ' ' + ('% 5d' % -10))
10
-10
<正负号>
>>> print(('%+5d' %10) + ' ' + ('%+5d' % -10))
+10
-10
3.4 字符串方法
字符串常量
{
string.digits 0~9
string.letters 所有字母 大小写
string.lowercase 所有小写字母
string.printable 所有课打印的字符的字符串
string.punctuation 包含所有标点的字符串
string.uppercase 所有大写字母的字符串
}
字符串常量(例如string.letters)与地区有区别,其本身取决于Python所配置的语言,如果可以确定自己使用的是ASCII那么就可以例如这样 string.ascii_letters
3.4.1 find (找到输出最左边,找不到输出-1)
>>> mark = "123456789123456789"
>>> mark.find("123456")
0
>>> mark.find("aasd")
-1
可接受区间定义 [)
{
>>> subject = "$$$ Get rich now!!! $$$"
>>> subject.find("$$$")
0
>>> subject.find("$$$" ,1)
20
>>> subject.find("!!!" ,0 ,16)
-1
}
3.4.2 join 非常重要的字符串方法,它是split方法的逆方法,用来在队列中添加元素
{
>>> seq = [1,2,3,4,5]
>>> sep = '+'
>>> sep.join(seq)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
sep.join(seq)
TypeError: sequence item 0: expected str instance, int found
>>> seq = ['1' ,'2' ,'3' ,'4' ,'5']
>>> sep.join(seq)
'1+2+3+4+5'
>>> sep
'+'
>>> seq
['1', '2', '3', '4', '5']
>>> dirs = '','usr','bin','env'
>>> '/'.join(dirs)
'/usr/bin/env'
>>> print ('C:' + '\'.join(dirs))
C:usrinenv
>>>
}
3.4.3 lower (title 所有首字母大写,其他小写)
lower方法返回字符串的小写字母版
{
>>> 'asdaADdasdwDsdw'.lower()
'asdaaddasdwdsdw'
>>> name = 'Gumby'
>>> names = ['gumby' ,'smith' ,'jones']
>>> if name.lower() in names : print ('Fount it!')
Fount it!
>>>
}
3.4.4 replace替换
{
>>> "This is a test".replace('is','eez')
'Theez eez a test'
}
3.4.5 split(jion的逆方法,用来将字符串分割成序列)。
{
>>> '1+2+3+4+5+6'.split('+')
['1', '2', '3', '4', '5', '6']
>>> '/use/dasd/w/ad/we'.split('/')
['', 'use', 'dasd', 'w', 'ad', 'we']
<如果不提供分割符,会把所有空格作为分隔符>
>>> "using the default ".split()
['using', 'the', 'default']
}
3.4.6 strip 去除字符串两边的空格(也可以指定去除字符)
{
>>> ' asdasd '.strip()
'asdasd'
>>> '000asd000asd00012'.strip('012')
'asd000asd'
}
3.4.7 translate 这3.5已经取消了,这个先不看了。