Python数据类型 -- 字符串

字符串:
1、 python 默认的文件编码都是ascii,所以要在编码的时候加上coding=utf-8,中文才不会乱码。
len 函数 是计算字符串的长度。
正确编码的长度。
b = '中文' , len(b) //长度是4
a = '中文'.decode('gbk')或utf-8
print len(a) // 长度是2

2、字符串前加r 是不转义字符串
如:a = r"\n"  会是\n的字符串,而不是空格
a = u"哈哈"不会转义uncode。

3、字符串替换
a = '123456789'
print a.replace('1','b')  把字符串a中的1换成b
以为str是不可变的,所以不能用a[1] = a 这样会报错。
修改完成要在赋值给变量

4、字符串拼接是+ (用6)用占位符也可以拼接字符串
a+b+c 这个很浪费性能的,因为python是不可变的,在相加的同时要创建两个临时对象,不推荐。

5、字符串模板 % 占位符。 (%s字符串,%d数字)
print "my name is %s caida" % "ssss" ,可以在一个字符串中添加数字
print "my name is %s and %s hah "  % ('one','two') 多个占位符的用元组,一 一对应的,用的比较多。
//字典替换方法
a = "this is %(name)s de %(who)s" % {'name':'my','who':'you'}
print a
format方法 字符串占位符
//不写东西默认顺序
a = "this is {} de {}".format('my','you')
print a
//this is my de you
//可以调整前后的顺序
a = "this is {1} de {0}".format('my','you')
print a
//this is you de my
//直接指定词
a = "this is {name} de {who}".format(name='my',who='you')
print a
推荐format方法 的第三个方法( 直接指定词)

使用模块替换字符串模板。
import string 
s=string.Template('$x,glorioux $x!')
x= s.substitute(x='ssss')
print x

d 是数字
f 是浮点数
s 是字符串
 
6、优秀的字符串拼接 join ***
a = '123456789'
b = 'aaaa'
c = '33afasfsf'
print ",".join([a,b,c])
//123456789,aaaa,33afasfsf
l = ['a','b','c']
s = ''.join(l)
print s


7、读写文本
w write  写入
r read   只读
a append 追加
d = open('a.txt','w')
d.write('hi,\nseaond.')
d.close()
help(d) #查看操作文件的方法
d = open('a.txt','r')
print d.read(100)
d.seek(0)//游标返回0

python内置模块读文件
import linecache
#读取文件的第一行
print linecache.getline('a.txt',1)
lines  = linecache.getlines('a.txt')
print lines
#['hi,\n', 'seaond.\n']
print type(lines) #把每一行变成一个list ,很好用


8、字符串切片
a = 'C:\Documents and Settings\Administrator.PC\.ssh'
print a[2:14]  从第二个提取,到第14个(1-14)
a = '123456789'
print a[1:9:3]
从第一个元素到第1个,后面的3表示步长,就是间隔
字符串也是一个序列,也可以用序列操作。

9、字符串三个引号的区别,''  " "  """ """
   单,双 都是,单行字符串,
   三个引号 是 多行字符串,可以原格式输出。

10 、字符串查找
a = "this is world"
print a.find('world')
print a[a.find('world'):] //返回找到的词
成功返回开始位置,失败返回-1
print help(a.find) //查看方法

11、字符串split  讲字符串分割成序列
两种取出am的方法。
s = "i,am,lilei"
#print s[s.find('am'):s.find('am')+2]
print  s.split(',')[1]

s = 'aaadd,ddss,ff'
ss = s.split()
print ss

12 ,把string帮助文档写入一个文件,用到标准输出流
import string  
import sys
a = help(string)
d = open('string.txt','w')
sys.stdout = d
help(string)
d.close

13、strip 去除两侧的空格。
s = '8# '
print len(s.strip('# ')) # 去掉# 和空格
lstrip #去左  rstrip去右


14 、maketrans和translate
import string
a = 'assdfafd2123saf'
#替换规则是一一对应的,a==@ , s==!
g = string.maketrans('as','@!')
print a.translate(g,'2') #第二个参数是删除,逐字删除的
#@!!df@fd13!@f
#他和a.replace的区别是,replace是整体替换是替换as的
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值