数据类型之 字符串一

字符串操作

创建及赋值



x = 'abcde'
x = "abcde"
x = '''abcde'''
x = """abcde"""
#通过str方法将其他类型转化为字符串类型
x = str([1234])



访问字符串

通过索引 和 通过切片访问任意部分字符串



astring = 'abcd'
#通过索引
print astring[1]
#通过切片从索引开始值到结束值前一个
print astring[0:3]



 修改字符串

字符串是不可变类型。不能直接修改字符串,只能通过创建新的字符串来进行'更新'.



astring1='hello world'
astring2='hello world'+'1'
id(astring1)==id(astring2)
False



 

删除字符和字符串

删除字符,字串

字符串是不可变类型。不能单独删除某个字符,可以通过剔除不需要的部分重新拼接。



astring = 'hello world'
#删除第二个'l'
#astring[:3] 为 'hel'  astring[4:] 为 ‘o world'
astring = astring[:3] + astring[4:]



删除整个字符串



#通过赋值空字符串
astring=''

#通过del删除字符串变量,此变量在下次定义前不可使用
del astring



 操作符

标准类型操作符

标准类型操作符全部适用于字符串

对象值操作符: = > >= < <= !=  <>

对象身份操作符: is  is not

布尔操作符:  and or not 

 

序列操作符 切片 

正序索引: 索引值始于0,结束于字符串长度减一。0< ind < len 

反向索引: 索引值始于-1,向字符串反向开始计数,结束于字符串长度的复述 -len(str)  -1< ind < -len(str)

默认索引:如果开始索引或结束索引没有指定,则分别以字符串的第一个和最后一个索引值为默认值



astring='abcdef'
#正向索引
astring[0:3]   #'abc'
astring[1:4]   #'bcd'
astring[-100:100]  
#反向索引
astring[-6:-3]  #'abc' 
astring[-5:-2]  #'bcd'
astring[-100:100]

默认索引
astring[:5]            #'abcde'
astring[0:5]          #'abcde'
astring[:-1]           #'abcde'
astring[-6:-1]        #'abcde'
astring[0:]             #'abcdef'
astring[0:None]     #'abcdef'
astring[-6:]           #'abcdef'
astring[-6:None]    #'abcdef'



成员操作符

in ,not in



astring = 'abcde'
'a' in astring
'c' not in astring



连接符 + 



’hello' + ' ' + 'world'



编译时字符串连接(不常用)

Python 允许在源码中将几个字符串连在一起写,来构建新的字符串。通过这种方法,可以把长的字符串分成几部分来写,而不用加反斜杠,这种写法的好处是可以把注释也加进来。



foo = 'hello' 'world'
foo = ('hello' 'world')

import urllib
f_url urllib.open('http://'
'localhost'
':8080'
'cgi-bin/fridnds2.py')



普通字符串转化为unicode字符串

使用u‘’ 或 unicode



x = u'unicode str'
x = unicode('unicode str'



如果普通字符串和unicode连接则会自动把普通字符转化为unicode字符串



x= u'unicode str'
y='normal str'
z=x+y
type(z)
<type 'unicode'>



 只适用于字符串的操作符

格式化操作符 %



# 字符串格式化符号

# %c转换成字符
# %s  优先使用str转换成字符串
# %r  优先使用repr转换成字符串
# %d/%i 转成有符号十进制数
#%u   转成无符号十进制数 
# %o  转成无符号八进制数
# %x/%X 转成无符号十六进制数
# %e/%E 转成科学计数法
# %f    转成浮点数
#%g %e/ %E / %f /%F的简写
#%% 输出%

# 格式化操作符辅助符号

# * 定义宽度或小数点精度
print '%3d' % 15 #位数不够用空格填充
# - 用作左对齐
print '%3d %-3d' % (15,15)
# + 在整数前面显示加号
print '%+3d' % 155 #位数不够用空格填充

# <sp> 在正数前面显示空格
print '% 3d' % 155

# # 在八进制前面显示零('0'),在十六进制前面显示'0x'或'0X'
print '%o %#o' % (15,15)   17 017
print '%x %#x' % (17,17)   11 0x11
# 0 显示的数字前面填充0 而不是默认的空格
print '%03d' % 15

# % '%%' 输出单一的%
print '%d%%' % 15

# (var) 映射变量
var1=15
print '%d' % (var1)

# m.n m表示最小总宽度,n表示小数点后的位数
print '%06.2f' % 15



字符串的独特特性

特殊字符串和控制字符

特殊字符包括反斜杠转移的那些都可以像普通字符一样存储到python的字符串中。例如\n \t \

控制字符通常用作字符串里的定界符 

三引号

三引号可以有效处理如换行符等特殊字符,他允许一个字符串跨多行,字符串中可以包含换行符,制表符,以及其他字符。

三引号自始至终保持一小块的字符串是所谓的WYSIWYG(所见即所得)格式的。

在写web网页或sql的时候特别有用



hi_1 = '''hi
there'''
hi_3 = 'hi\
there'

errHTML = '''
<html><head><title>
Firends CGI Demo </title></head>
<body><h3>ERROR </h3>
<b>%s</b><p>
<form><input type=button value=back 
onlick="window.history.back()" </form>
</body><html>
'''

cursor.execute('''
        create table users(
        login varchar(8),
        uid integer,
        prid integer)
''')



字符串的不变性

字符串是一种不可变的数据类型,他的值不能被改变或修改的。可以通过id()来深入了解 。

对于字符串赋值时,左值必须是完整的,即左值必须是一个字符串对象,不能是字符串的一部分。



s='abc'
id(s)
40244288
##对字符串进行"修改"
s=s+'def'  
id(s)
40247712

#左值不是一个完整的字符对象,会报TypeError
>>> s[0]='b'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment



 

内建函数

标准类型内建函数



#标准类型内建函数
cmp(obj1,obj2) type(obj) repr(obj) str(obj) type(obj)
x='abc'
y='abc'
cmp(x,y)  # 0
type(x)   # <type 'str'>  
repr(x)   # "'xyz'"
str(x)    #  'xyz'



序列类型内建函数



#序列类型内建函数

#len() max() min() enumerate() zip() sorted() reversed() sum()
x = 'abc'
y = 'zyz'
#len函数返回序列的长度
len(x)
#max函数返回序列中的最大值,min函数返回序列中的最小值
max(x)
min(x)
#enumerate 函数接收一个可迭代对象为参数,同时返回一个enumerate 对象,enumerate对象由 index和item值组成。
z = enumerate(x)
for x, y  in z:
    print x,y

#zip 返回一个列表,其第一个元素是it9 it1 这些元素的第一个元素组成的元组,第二个一次类推。元组个数等于两个参数中迭代元素的最小值
x1,x2,x3='ab','abc','abc'
y1,y2,y3='xyz','xyz','xy'
zip(x1,y1)
[('a', 'x'), ('b', 'y')]
zip(x2,y2)
[('a', 'x'), ('b', 'y'), ('c', 'z')]
zip(x3,y3)
[('a', 'x'), ('b', 'y')]

#sorted(seq,reverse=False) 接收一个可迭代对象为参数,返回一个有序列表,可修改reverse的参数值
sorted(x)
['a', 'b']
sorted(x,reverse=True)
['b', 'a']

# reversed接收一个序列作为参数,返回一个逆序的迭代器
>>> reversed(x)
<reversed object at 0x02628B10>
>>> z=reversed(x)
>>> for x in z:
...     print x
...
b
a
#sum函数 不支持str类型



字符串类型函数

raw_input() input() 接收用户输入参数,并将这个输入返回. 2.7 中 input需要注意用户注意python语法,所以raw_input更适合



#input需要注意遵循python规则,如果想要输入字符串 则要 加引号
user_raw_input=raw_input('please enter your input : ')
please enter your input : 4
user_input=input('please enter your input :')
please enter your input :4
print type(user_raw_input)
<type 'str'>
print type(user_input)
<type 'int'>
user_input=input('please enter your input :')
please enter your input :’hahah'
print type(user_input)
<type 'str'>



str 和 unicode 

str和unicode都是工厂函数,接收任意类型对象,然后创建该对象的可打印或者unicode的字符串表示。



isinstance(u'\0xAB',str)          #False
not isinstance('foo',unicode)     #True
isinstance(u'0xAB',basestring)    #True
isinstance('foo', basestring)     #True



 

chr() unichr() ord()

chr() 函数用一个范围在0 到255de 参数做整数,并返回,对象的asicc码字符.

unichr()和 chr()功能一样不过返回的unicode字符

ord()函数是chr()的配对函数,接收一个长度为1的字符串作为参数,并返回对应的asicc码值,或unicode值



chr(65)
'A'
ord('A')
65
unichr(65)
u'A'
ord(u'A')
65



 

字符串内建函数



############大小写相关#############
#首字母大写
str.capitalize()

#将字符串改为小写
str.lower()
str.casefold()  #python3 中 功能比lower强大

#将字符串改为大写
str.upper() 

#字符串居中,fillchar只能为一个字符
str.upper(width,fillchar=None)

# 转换为title格式 ,所有字符串首字母大写
str.title()

# 字符串大小写全部反转
str.swapcase() 


############格式化输出#############
#格式化输出
#字符串居中,fillchar只能为一个字符
str.center(10,'*') #将x居中,共10位长度,用*填充 ,右边可能比左边多一位
#字符串左对齐,在指定字符串长度后,未指定fillchar默认用空格补齐
str.ljust(width[, fillchar]) 
#字符串右对齐,在指定字符串长度后,未指定fillchar默认用空格补齐
str.rjust(width[, fillchar]) 

#zfill函数返回字符串以0填充到指定位字符串。
str.zfill(width)
x='hello world nihao'
x.zfill(20)
'000hello world nihao'

##############查找##############
#查找位置,从start开始end前结束
str.find(sub,start=None,end=None)  sunstring 找不到则返回-1 
str.index(sub,start=None,end=None) substring 找不到会报ValueError: substring not found的错误,建议用find函数。
str.rfind(sub[, start[, end]])  从右往左查询 找不到返回-1
str.rindex(sub[, start[, end]])  从右往左查询

#计算子字符串在选定范围内出现的次数
str.count(sub,start=None,end=None)


##############替换修改##############
#tab扩展将tab替换为空格,每个tab中间间隔tabsize
str.expandtabs(tabsize)
x='a\tbb\tccc\tdddd\teeeee\tffffff\tggggggg\thhhhhhhh\tiiiiiiiii\tjjjjjjjjjj\t'
print x
ex_x=x.expandtabs(16)
print ex_x

#strip删除左右两边符合条件的substr,并返回修改后的字符串,不指定子串则删除空白字符。
str.rstrip([chars]) 
str.lstrip([chars]) 
str.strip([chars]) 
x='hello world'
x.strip('held')  # 删除 'hel'后 'lo world'仍然有l在字串中所以继续删除,直到删除不了
'o wor'
x.rstrip('held')
'hello wor'
x.lstrip('held')
'o world'

# 分割字符串 按指定分割符分隔字符串
#指定分割符分割
str.split([sep[, maxsplit]]) 
str.rsplit([sep[, maxsplit]]) 
x='hello world nihao'
 x.rsplit(' ' ,1)
['hello world', 'nihao']
 x.split(' ' ,1)
['hello', 'world nihao']
#按换行符分割 keepends表示是否保留分隔符
str.splitlines([keepends]) 
 x
'haha\nhaha2\nhaha3'
 x.split('\n')
['haha', 'haha2', 'haha3']
x.splitlines()
['haha', 'haha2', 'haha3']
x.splitlines(True)
['haha\n', 'haha2\n', 'haha3']
str.replace(old, new[, count]) 

#类似于split 区别是 返回元组,并且只分割一次,
str.partition(sep) 

x='hello world nihao'
x.partition(' ')
('hello', ' ', 'world nihao')
x.rpartition(' ')
('hello world', ' ', 'nihao')

#替换字符串函数 replace
str.replace(old, new[, count])  如果指定count那么最多只进行count次转换
x='hello world nihao'
x.replace('o','oo')
'helloo woorld nihaoo'
x.replace('o','oo',2)
'helloo woorld nihao'

#translate 方法根据maketrans 给的字符串映射来替换字符串
#如果table没有指定为None,那么将删除deletechars中的字符串
str.translate(table[, deletechars]) 
#不指定映射表
x='hello world nihao'
x.translate(None,'oel')
'h wrd niha'
#设置映射表,那么将先删除字符串然后,进行映射转换
import string
xset=string.maketrans('oel','xyz') 
#xset=str.maketrans('oel','xyz')  #python3 中无需import string str即可调用 maketrans()
#不指定deletechar
x.translate(xset)
'hyzzx wxrzd nihax'
xset=string.maketrans('oelh','xyzk')
#不指定deletechar
 x.translate(xset)
'kyzzx wxrzd nikax'
#指定deletechar
x.translate(xset,'oel')
'k wrd nika'

##############判断##############
#判断是否以字符串为开始 注意是 starts
str.startswith(suffix,start=None,end=None)

#判断是否以字符串为结尾 注意是 ends
str.endswith(suffix.start=None,end=None)

#判读字符串是否完全是空格
str.isspace()

#判断字符串中是否只以 字母,数字组成
str.isalnum()

#判断字符串中是否是数字组成
str.isdigit()  
unicode.isdecimal() python2中必须是unicode才能用此方法,python3可直接使用
unicode.isnumeric() python2中必须是unicode才能用此方法,python3可直接使用

#判断字符串是否可以作为标识符 
str.isidentifier() 

#判断字符串是否可以直接显示\n\t \\ \%这些转义字符无法直接显示
str.isprintable() 

#判断字符串是否为title格式
str.istitle()

#判断字符串是否为小写格式
str.islower() 

#判断字符串是否为大写格式
str.isupper()



 

字符串格式化输出

python 2.6之前使用 % python 2.6 引入了str.format()函数功能强大。

% 参考 格式化操作符 % 一节

str.format()函数方法



#语法
#format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]
#format_spec ::= [[填充字符]对齐方向][正负符号][#八/六进制][0 十进制][宽度,][.精度][类型]
#fill        ::=  <any character>
#align       ::=  "<" | ">" | "=" | "^"
#sign        ::=  "+" | "-" | " "
#width       ::=  integer
#precision   ::=  integer
#type        ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

#format 语法中使用'{03.2f}' 等价于旧方法%的 '%03.2f'
#{空白|位置|参数名|参数属性|参数项format_spec}

#1 通过参数位置
 '{0}, {1}, {2}'.format('ccc', 14, 'male')
#2 通过参数名
'{name}, {age}, {sex}'.format(age=14, sex='male', name='ccc')
#3 通过参数属性 此时必须指定参数名或参数位置
class Student():
    def __init__(self,name,age,sex):
        self.name=name
        self.age=age
        self.sex=sex
stu=Student('ccc',14,'male')
#通过参数位置调用参数属性
'{0.name}, {0.age}, {0.sex}'.format(stu)
#通过参数名调用参数属性
'{stu1.name}, {stu1.age}, {stu1.sex}'.format(stu1=stu)

#4 通过参数中的元素, 一般为可迭代 此时必须指定参数名或参数位置
x=['ccc',14,'male']
#通过参数位置调用参数元素
'{0[0]}, {0[1]}, {0[2]}'.format(x)
#通过参数名调用参数元素
'{stu1[0]}, {stu1[1]}, {stu1[2]}'.format(stu1=x)

#替换老式方法中%r %s
#注意!r 即repr()的输出。
'{!r} {!s} {!s}'.format('ccc', str(14), 'male')
'{!r} {!s} {!s}'.format('ccc', str(14), 'male')
"'ccc' 14 male"

#指定对齐方式及宽度输出
#左对齐
'{0:<30}'.format('left aligned')
#右对齐
'{0:>30}'.format('right aligned')
#居中显示
'{0:^30}'.format('center aligned')
# 数字的时候使用‘=’强制让对齐补齐放在符号位后边
>>> '{0:=+30}'.format(155)
'+                          155'
>>> '{0:=+30}'.format(-155)
'-                          155'

#替换老式方法中 %+f %-f % f 
>>> '{0: f}; {1: f}'.format(3.14, -3.14)
' 3.140000; -3.140000'
>>> '{0:+f}; {1:+f}'.format(3.14, -3.14)
'+3.140000; -3.140000'
>>> '{0:-f}; {1:-f}'.format(3.14, -3.14)
'3.140000; -3.140000'

#替换老式方法中的八进制和十六进制
>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
>>> "int: {0:0d};  hex: {0:#x};  oct: {0:#o};  bin: {0:b}".format(42)
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 101010'

#显示百分号%
>>> 'Correct answers: {:.2%}'.format(0.253)
'Correct answers: 25.30%'

#显示时间
>>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2010-07-04 12:15:58'