字符串

# coding:utf-8python

#字符串是不可变,不可修改web

#----------------------------------------- 字符串格式化 ------------------------------------------------------------shell

#基本字符串操做api

#索引,分片,乘法,判断成员资格,求长度,取最小值和最大值 对字符串都适用ide

#请记住字符串是不可变的。所以以下所示的项或分片赋值都是不合法的:函数

#webite = 'http://www.python.org'ui

#webite[-3:] = 'com'spa


#字符串格式化操做符unix

format = "Hello, %s, %s enough for ya?"     #格式化字符串的%s部分称为说明符,它们标记了须要植入转换值的位置。S表示值会被格式化,若是不是字符串,则会用str将其转换为字符串。orm

values = ('world', 'Hot')       #一个值能够用字符串或数字,多个值只能用元组或者字典,若是用列表只能算一个值

print format % values

#Hello, world, Hot enough for ya?

#注意:格式化字符包括百分号,请使用%%


#字符串格式化浮点数

#若是要格式化浮点数,可使用f说明转换说明符的类型。同时提供所需的精度:一个句点再加上但愿保留的小数位数。由于格式化转换说明符老是以表示类型的字符结束,因此精度应该放在类型字符f的前面

format = "Pi with three decimals: %.3f"    #f说明付的类型,.3是小数位

from math import pi         #导入pi函数

print format % pi

#Pi with three decimals: 3.142


#string模块字符串格式化方法

from string import Template     #string模块的Template模板字符串

s = Template('$x, glorious $x!')        #工做方式相似不少unix shell里的变量替换。

print s.substitute(x='slurm')         #substitute模板方法传递关键字参数替换字符串中的$x

#slurm, glorious slurm!

s = Template("It's ${x}tastic!")     #若是替换字段是单词一部分,那么参数名就必须用括号括起来

print s.substitute(x='slurm')

#It's slurmtastic!

s = Template("Make $$ selling $x!")  #可使用$$插入美圆符号

print s.substitute(x='slurm')

#Make $ selling slurm!

s = Template('A $thing must nerver $action.')

d = {}

d['thing'] = 'gentlemen'            #除了关键字参数以外,还可使用字典变量提供值

d['action'] = 'show his socks'

print s.substitute(d)

#A gentlemen must nerver show his socks.

#使用元组为格式化字符,必须用括号

print '%s plus %s equals %s' % (1, 1, 2)

#1 plus 1 equals 2


#转换类型

#d, i       带符号的十进制整数

#o          不带符号的八进制

#u          不带符号的十进制

#x          不带符号的十六进制(小写)

#X          不带符号的十六进制(大写)

#e          科学计数法表示的浮点数(小写)

#E          科学计数法表示的浮点数(大写)

#f, F       十进制浮点数

#g          若是指数大于-4或者小于精度值则和e相同,其余状况和f相同

#G          若是指数大于-4或者小于精度值则和E相同,其余状况和F相同

#C          单字符(接受整数或者单字符字符串)

#r          字符串(使用repr转换任意Python对象)

#s          字符串(使用str转换任意Python对象)


#简单转换

print 'Price of eggs: $%d' % 42   # %d是带符号的十进制整数

#Price of eggs: $42

print 'Hexadecimal price of eggs: %x' % 42   # %x是不带符号的十六进制(小写)

#Hexadecimal price of eggs: 2a

from math import pi

print 'Pi: %f...' % pi      # %f是十进制浮点数

#Pi: 3.141593...

print 'Very inexact estimate of pi: %i' % pi   # %i和%d 是同样的

#Very inexact estimate of pi: 3

print 'Using str: %s' % 42L         # %s 普通字符串

#Using str: 42

print 'Using repr: %r' % 42L        # %r python字符串

#Using repr: 42L


#字段宽度和精度

#字宽度一共有多少位字符,若是宽度过长,前面用空格代替,精度对于数字来讲是小数点后面保留几位,对于字符串来讲转换后的值所能包含的最大字符个数。

from math import pi

print '%10f' % pi                   #字段宽度 10

#  3.141593

print '%10.2f' % pi                #字段宽 10,精度 2

#      3.14

print '%.2f' % pi                   #精度 2

#3.14

print '%.11s' % 'Guido van Rossum'         #字符串方式

#Guido van R

print '%.5s' % 'Guido van Rossum'

#Guido

print '%.*s' % (5, 'Guido van Rossum')      #能够用星号做为字段宽和精度,数值从元组参数中读出

#Guido


#符号,对齐和用0填充

#在字符宽度和精度值以前还能够放置一个”标志“,该标志能够是零,加号,减号或空格(就是将原来空格替换掉)。

print '%010.2f' % pi               #字段宽 10 ,并用0填充

#0000003.14

print '%-10.2f' % pi                #减号左对齐数值,右侧多出额外空格

#3.14

print ('% 5d' % 10) + '\n' + ('% 5d' % -10)     #空格意味着在正数前加上空格。这在须要对齐正负数时会颇有用。

#   10

#  -10

print ('%+5d' % 10) + '\n' + ('%+5d' % -10)     #加号无论是正数仍是负数都标示出符号(一样是在对齐时颇有用)。

#  +10

#  -10


#------------------------------------------  字符串方法  --------------------------------------------------------


#find

#find方法能够在一个较长的字符串中查找子串。它返回子串所在位置的最左端索引。若是没有找到则返回-1。

print 'With a moo-moo here, and a moo-moo there'.find('moo')    #查找moo,返回所在位置最左端的索引

#7

title = "Monty Python's Flying Circus"

print title.find('Monty')           #最左端索引位置0

#0

print title.find('Python')          #最左端索引位置6

#6

print title.find('Flying')          #最左端索引位置15

#15

print title.find('Zirquss')         #没找到显示-1

#-1

subject = '$$$ Get rich now!!! $$$'

print subject.find('$$$')        #找到$$$,返回0,证实在索引0位置找到子串

#0

print subject.find('$$$', 1)        #起始点索引位置1开始查找,找到后面第二个$$$,索引位置是20

#20

print subject.find('!!!')           #索引位置16找到

#16

print subject.find('!!!', 0, 16)    #起始点索引为0和结束点索引为16范围内查找,没有找到

#-1

print subject.find('!!!', 0, 19)    #起始点索引为0和结束点索引为19范围内查找,找到

#16


#join

#split逆方法,用来链接序列中的元素。

#seq = [1, 2, 3, 4, 5]

#sep = '+'

#print sep.join(seq)   #列表没法join,必须都是字符串

seq = ['1', '2', '3', '4', '5']

sep = '+'

print sep.join(seq)     #链接字符串列表

#1+2+3+4+5

dirs = '', 'usr', 'bin', 'env'

print  '/'.join(dirs)

#/usr/bin/env

print 'C:' + '\\'.join(dirs)

#C:\usr\bin\env


#lower

#返回字符串的小写字母

print 'Trondheim Hammer Dance'.lower()

#trondheim hammer dance

#用户输入大写字母,能够用来变成小写并查找到(忽略大写)

name = 'Gumby'

names = ['gumby', 'smith', 'jones']

if name.lower() in names: print 'Found it!'

#Found it!


#replace

#replace方法返回某字符串的全部匹配项均被替换以后获得字符串

print 'This is a test'.replace('is', 'eez')

#Theez eez a test


#split

#join逆方法,字符串分割成序列

print '1+2+3+4+5'.split('+')

#['1', '2', '3', '4', '5']

print '/usr/bin/env'.split('/')

#['', 'usr', 'bin', 'env']

print 'Using the default'.split()   #若是不提供任何分隔符,程序会把全部空格做为分隔符(空格,制表,换行等)

#['Using', 'the', 'default']


#strip

#strip方法返回去除两侧(不包括)内部空格的字符串

print '   internal whitespace is kept    '.strip()

#internal whitespace is kept

#用户若是输入值带有空格。

names = ['gumby', 'smith', 'jones']

name = 'gumby   '

if name in names: print 'Found it!'           #这样匹配不到

if name.strip() in names: print 'Found it!'   #能够匹配

#Found it!

#也能够指定须要去除的字符串,将它们列为参数便可。

print '*** SPAM * for * everyone!!! ***'.strip(' *!')    #这个方法只会去除两侧字符,因此字符串中的星号没有被去掉

#SPAM * for * everyone


#translate

#和replace同样替换,但translate只替换单个字符,能够同时进行多个替换。

from string import maketrans

table = maketrans('cs', 'kz')     #将模板maketrans里面的c替换k,s替换成z

print len(table)        #多少字符串

#256

print table[97:123]

#abkdefghijklmnopqrztuvwxyz

print maketrans('', '')[97:123]

#abcdefghijklmnopqrstuvwxyz


#涉及的函数

#string.capwords(s[, sep])          使用split函数分割字符串s(以sep为分隔符),使用capitalize函数将分割获得的各单词首字母大写,而且使用join函数以sep为分隔符将各单词链接起来

#string.maketrans(from, to)         建立用于转换的转换表。

相关文章
相关标签/搜索