python2学习笔记--字符串(第3章)

来源:互联网 发布:淘宝旺旺客服模板代码 编辑:程序博客网 时间:2024/06/01 21:26

1.单引号字符串'hello,world' 和双引号字符串 "hello,world" 没有区别

反斜线转义 'let\'s go'避免歧义

2."hello" "world",相邻的字符串会自动拼接->"helloworld",但正常拼接字符串用+号,

"hello"+"world"

3.str 会把值转换成合理的字符串形式,当用print的时候会得到用户所见结果

   repr函数会创建字符串,以python合法表达式来表示值,print时是python内部代码形式

4.长字符串'''...'''或"""...""", 原始字符串r"...",最后一个字符不能为\,Unicode字符串u"...".

/*********************************/

/*********************************/

字符串方法:

substitute():用传进来的关键字参数foo替换字符串参数$foo

from string import Template

s = Template("$x,glorious $x!")

s.substitute(x='slurm')


find():在一个较长的字符串中寻找子串,返回子串最左端索引,没找到返回-1;


join(): 用来连接序列中的元素

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

'+'.join(seq)

>>>1+2+3+4


lower():返回字符串中的小写字母版

'Hello,World'.lower()

>>>hello,world


replace():返回被替换后得到的字符串

'This is a ...'.replace('is','as')

>>>'This as a...'


split():join的逆方法,将字符串分割成序列,没提供分隔符时,会将空格等作为分隔符


strip():去除字符串两侧指定的字符


translate():配合maketrans()函数进行字符(单个字符)替换,注意与replace()的区别



阅读全文
0 0
原创粉丝点击