当下 ║ 2018.08.14
人生苦短,我们都要用Python,大家要经常回看大纲~
考试内容二、Python语言基本数据类型
第四部分:字符串类型的操作:字符串操作符、处理函数和处理方法。
字符串操作符
常用的字符串操作符有
x+y:连接两个字符串x和y
x*n:复制n次字符串x
下表实例变量a值为字符串 "Hello",b变量值为 "Python":
字符串处理函数和处理方法
len(x):字符串的长度;
str(x):任意类型x转为字符串形式;
hex(x):整数x转为十六进制小写形式字符串;
oct(x):整数x转为八进制小写形式字符串;
chr(x):x为unicode编码,返回对应的字符;
ord(x):x为字符,返回对应的Unicode编码;
str.*形式的函数
str.lower()或者str.upper():返回字符串的副本,全部字符小写或者大写;
str.count(sub):返回子串sub在str中出现的次数;
str.center(width[,fillchar]):字符串str根据宽度width居中,fillchar可选,默认为空格;
>>> s='abdDEFG'
>>> s.lower()
'abddefg'
>>> s.upper()
'ABDDEFG'
>>> s.count('d')
1
>>> s.center(20)
' abdDEFG '
>>> s.center(20,'*')
'******abdDEFG*******
find 方法
作用:在一个较长字符串中查找子串。返回子串所在位置的最左端索引,如果没有找到则返回-1.如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。
用法:string.find()
>>> a = 'i am a boy with no money'
>>> print a.find('a')
2
>>> print a.find('a',10,len(a))
-1 #在字符串a的第10到最后一位无法找到字符a,则返回-1
>>> sep = '+'
>>> print sep.join(seq)
1+2+3+4+5
>>> dirs = '','usr','bin','env'
>>> print '/'.join(dirs)
/usr/bin/env
>>> print os.path.join('/hello/','good/boy/','doiido')
/hello/good/boy/doiido
replace 方法
作用:Python replace()方法把字符串中的old(旧字符串)替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
语法:str.replace(old, new[, max])
参数:
old – 将被替换的子字符串。
new – 新字符串,用于替换old子字符串。
max – 可选字符串, 替换不超过 max 次
>>> str = "this is string example....wow!!! this is really string"
>>> print str.replace("is", "was")
thwas was string example....wow!!! thwas was really string
>>> print str.replace("is", "was", 3)
thwas was string example....wow!!! thwas is really string
split方法
Python split()通过指定分隔符对字符串进行切片,如果参数num有指定值,则仅分隔 num 个子字符串
split()方法语法:
str.split(str=”“, num=string.count(str)).
参数
str –分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
num –分割次数。
返回分割后的字符串列表。
>>> str = "Line1-abcdef \nLine2-abc \nLine4-abcd"
>>> print str.split( )
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
>>> print str.split(' ', 1 )
['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
该来的终究会来,没有任何例外和奇迹。
E
N
D
领取专属 10元无门槛券
私享最新 技术干货