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

python中的字符串

2016-04-10 20:37 441 查看
python字符串

1.     单引号和双引号作用相同

2.     字符串格式化方法

 .upper():       把所有字母转换为大写                                                ‘HELLOWWORLD’

 .lower():       把所有字母转换为小写                                                ‘helloworld’

 .capitalize():把字符串中的首字母大写,并把剩余字母转换为小写   ‘Helloworld’

 .title():          把首字母以及每个空格或者标点符号后面的字母转换为大写。其他字母转换为小写                                                                                                  ‘HelloWorld’

3.     数学运算与比较运算

+:  连接两个字符串

*:将原来的字符串重复五次

>>>a='hellow'

>>> a+a

'hellowhellow'

>>> a*5

'hellowhellowhellowhellowhellow'

4.     删除空格

.strip():     删除开头和结尾的所有的空格

.rstrip():    删除末尾的空格

.lstrip();    删除开头的空格

函数里可以传值

>>>a='   hello word '

>>>a.strip()

'helloword'

>>>a.lstrip()

'helloword '

>>>a.rstrip()

'   hello word'

 

>>>a="####hello world ###"

>>>a.lstrip()

'####helloworld ###'

>>>a.lstrip('#')

'hello world ###'

5.     查找和替换文本

count():   返回一个字符串在另一个字符串中出现的次数

>>>long_text='the book is very the man'

>>>long_text.count('t')

       find():语法

              str.find(str,beg=0,end=len(string))

              str–指定检索的字符串

              beg—开始索引,默认为0

              end—结束索引,默认为字符串的长度

              返回值:如果包含子字符串返回开始的索引值,否则返回-1

>>> a

'####hello world ###'

>>> a.find('h',3,9)

       replace():synax

       str.repalce(old,new,max)

>>> a

'####hello world ###'

>>> a.replace('hello','HELLO')

'####HELLO world ###'

字符串中的 old(旧字符串)替换成 new(新字符串),如果指定第三个参数max,则替换不超过
max 次。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python