python中string.digits_python学习笔记五:字符串方法

常用字符串常量:

string.digits:包含数字0~9的字符串

string.letters:包含所有字母(大写或小写字符串,在python3.0中,使用string.ascii-letters代替)

string.lowercase:包含所有小写字母的字符串

string.printable:包含所有可打印字符的字符串

string.punctuation:包含所有标点的字符串

string.uppercase:包含所有大写字母的字符串

1)find:在较长的字符串中查找子串,返回子串所在位置最左端索引,如果没找到,则返回-1

>>>

title = "Monty Python's Flying Circus"

>>>

title.find('Monty')

0

>>>

title.find('Python')

6

接受可选的起始点和结束点参数:

>>>

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

>>>

subject.find('$$$',1)

21

>>>

subject.find('!!!',1,16)

-1

2)join:用来连接序列中的元素,且必须是字符串,语法格式:连接符.join(字符串)

>>>

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

>>>

sep = '+'

>>>

sep.join(seq)

'1+2+3+4+5'

>>>

dir = '', 'usr', 'bin', 'env'

>>>

'/'.join(dir)

'/usr/bin/env'

3)lower:返回字符串的小写字母

>>> 'Trondheim Hammer Dance'.lower()

'trondheim hammer dance'

>>>

>>>

>>> name = 'Gumby'

>>> names = ['gumby', 'smith', 'Jones']

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

...

Found it

标题转换:

title方法:所有单词首字母大写,而其他字母小写

>>>

"that's all folks".title()

"That'S

All Folks"

>>>

capword函数:

>>>

import string

>>>

string.capwords("that's all folks")

"That's

All Folks"

4)replace:返回某字符串的所有匹配项均被替换之后得到字符串,即查找替换

>>>

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

'Theez

eez a test'

5)split:join的逆方法,用来将字符串分割成序列

>>>

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

['1',

'2', '3', '4', '5']

6)strip:返回去除两侧(不包含内部)空格(默认情况下)的字符串

>>>

'          internal whitespace krpt                 '.strip()

'internal

whitespace krpt'

指定分隔符:

>>>

'*** SPAM * for * everyone !!! ***'.strip(' *!')

'SPAM

* for * everyone'

7)translate:替换字符串的某些部分,只处理单个字符,优势在于可以同时进行多个替换,替换之前,需要先完成一张转换表,使用string模块的maketrans函数

>>>

from string import maketrans

>>>

table = maketrans('cs', 'kz')

>>>

len(table)

256

>>> 'this is an incredible

test'.translate(table, ' ')#第二个参数可选,指定需要删除的字符

'thizizaninkredibletezt'

  • 3
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值