您的位置:首页 > 编程语言 > Python开发

Python数据类型String字符串

2017-06-26 19:47 459 查看

1、转义字符



2、字符串运算符

操作符描述例:a=”hello”
+字符串连接a + ” world” #hello world
*重复输出字符a * 2 #hellohello
[]通过索引(0开始)获取字符串中字符a[0] #h
[ : ]截取字符串指定索引的字符a[0:5] #hello
in字符串包含指定字符返回True反之False“o” in a #True
not in字符串不包含指定字符返回True反之False“o” in a #False
r/R所有的字符串都是直接按照字面的意思来使用r’\n’ #\n

3、字符串格式化





4、Unicode 字符串

定义:u’hello’

5、字符串内建函数

操作符描述例:str=”hello world”
str.replace(old,new,count)将字符串中旧字符串替换成新字符串,替换次数str.replace(‘l’,’o’,1) #heolo world
str.split(str,count)指定分隔符指定分割词素返回字符串列表str.split(’ ‘,1) #[‘hello’, ‘world’]
str.partition(str)指定分隔符将字符串进行分隔成元组str = “hello/world” str.partition(‘/’) #(‘hello’, ‘/’, ‘world’)
str.find(str,start,stop)指定字符串开始和结束搜索位置搜索指定字符第一个的索引位置str.find(‘o’,5,10) #7
str.rfind(str,start,stop)指定字符串开始和结束搜索位置搜索指定字符最后一个的索引位置str.rfind(‘l’) #9
format格式化字符串“{0} {1}”.format(“hello”,”world”) #hello world
str.index(str,start,stop)指定字符串开始和结束搜索位置搜索指定字符第一个的索引位置str.index(‘o’,5,10) #7
str.rindex(str,start,stop)指定字符串开始和结束搜索位置搜索指定字符最后一个的索引位str.rindex(‘o’,5,10) #7
str.count(str,start,stop)指定字符串开始和结束搜索位置搜索指定字符次数str.count(‘h’,0,10) #1
str.encode(encoding,errors)以指定编码格式编码字符串,不同错误处理方案默认strictstr.encode(‘base64’,’strict’) #aGVsbG8gd29ybGQ=
str.decode(encoding,errors)以指定编码格式解码字符串,不同错误处理方案默认strictstr=”aGVsbG8gd29ybGQ=” str.decode(‘base64’,’strict’) #hello world
str.join(连接的序列)将序列中的元素以指定的字符连接生成一个新的字符串str=”&” list = (“a”,”b”,”c”) str.join(list) #a&b&c
str.startswith(str,start,stop)指定字符串开始和结束搜索位置搜索指定前缀字符返回True,反之Falsestr.startswith(‘h’,0,11) #True
str.endswith(str,start,stop)指定字符串开始和结束搜索位置搜索指定后缀字符返回True,反之Falsestr.endswith(‘d’,0,11) #True
str.isupper()检测字符串中所有字母是否都为大写,是返回True反之FalseFalse
str.istitle()检测字符串中所有单词拼写首字母是否为大写,且其他字母为小写,是返回True反之FalseFalse
str.lower()转换字符串中所有大写字符为小写hello world
str.upper()转换字符串中所有小写字符为大写HELLO WORLD
str.capitalize()将字符串的第一个字母变成大写,其他字母变小写Hello world
str.isspace()检测字符串是否只由空格组成,是返回True反之FalseTrue
str.islower()检测字符串是否由小写字母组成,是返回True反之FalseTrue
str.isalpha()检测字符串是否由字母组成,是返回True反之FalseFalse带空格了
str.isdigit()检测字符串是否只由数字组成,是返回True反之FalseFalse
str.isnumeric()检测unicode字符串是否只由数字组成,是返回True反之FalseFalse
u”hello”.isdecimal()检查unicode字符串是否只包含十进制字符,是返回True反之FalseFalse
str.isalnum()检测字符串是否由字母和数字组成,是返回True,反之FalseFalse
str.center(strlength,fillstr)原字符居中,填充字符填充至总长度str.center(15,’m’) #mmhello worldmm
str.ljust(newlen,str)原字符串左对齐使用指定字符填充至指定长度的新字符串str.ljust(15,’0’) #hello world0000
str.rjust(newlen,str)原字符串右对齐使用指定字符填充至指定长度的新字符串str.rjust(15,’0’) #0000hello world
str.zfill(newlen)原字符串右对齐使用0填充至指定长度的新字符串str.rjust(15,’0’) #0000hello world
min(str)字符串中最小的字母空格
max(str)字符串中最大的字母w
str.expandtabs(x)把字符串中\t转为x个空格str=”hello\tworld” str.expandtabs(3) #hello world
str.rstrip(str)删除末尾指定字符str.rstrip(‘d’) #hello worl
str.strip(str)删除字符串头尾指定字符str.strip(‘d’) #hello worl
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: