Python 基础 - 字符串

>>> ' spam eggs'
' spam eggs'
>>> ' doesn\' t'
" doesn' t"
>>> ' doesn\'t'
" doesn't"
>>> u'hello world!'
u'hello world!'
>>> " doesn't "
" doesn't "
>>> ' "Yes," he said.'
' "Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
>>>



>>> hello = " This is a rather long string containing\n\
... serveral lines of text just as you would do in C. \n\
... Note that whitespace at the beginning of the line is \
... significant."
>>> print hello
This is a rather long string containing
serveral lines of text just as you would do in C.
Note that whitespace at the beginning of the line is significant.
>>>

>>> hello = r" This is a rather long string containing \n\
... serveral lines of text much as you would do in C."
>>> print hello
This is a rather long string containing \n\
serveral lines of text much as you would do in C.
>>>



或者,字符串可以用一对三重引号”””或'''来标识。三重引号中的字符串在行尾不需要换行标记,所有的格式都会包括在字符串中。

>>> print """
... Usage:thingy [OPTIONS]
... -h
... -H
... """

Usage:thingy [OPTIONS]
-h
-H

>>> # 跟php的第三种字符串表示方法。

字符串可以用+号联接(或者说粘合),也可以用*号循环。

>>> word = 'help' + 'A'
>>> word
'helpA'
>>> '<' + word*5 + '>'
'<helpAhelpAhelpAhelpAhelpA>'
>>>

两个字符串值之间的联接是自动的,上例第一行可以写成“word = 'Help' 'A'这种方式只对字符串值有效,任何字符串表达式都不适用这种方法。

>>> import string
>>> 'str' 'ing' #只对字符串值有效
'string'
>>> string.strip('str')+'ing'
'string'
>>> string.strip('str') 'ing' #任何字符串表达式都不适用这种方法。
File "<stdin>", line 1
string.strip('str') 'ing'
^
SyntaxError: invalid syntax
>>>

字符串可以用下标(索引)查询;就像C一样,字符串的第一个字符下标是0。这里没有独立的字符类型,字符仅仅是大小为一的字符串。就像在Icon中那样,字符串的子串可以通过切片标志来表示:两个由冒号隔开的索引。

>>> word[4]
'A'
>>> word[0]
'h'
>>> word
'helpA'
>>>

切片索引可以使用默认值;省略前一个索引表示0,省略后一个索引表示被切片的字符串的长度。

>>> word[:2]
'he'
>>> word[2:]
'lpA'
>>>


len():内置函数

C字符串不同,Python字符串不能改写。按字符串索引赋值会产生错误。

然而,可以通过简单有效的组合方式生成新的字符串:

>>> 'x' + word[1:]
'xelpA'
>>> 'Splat' + word[4]
'SplatA'

切片操作有一个很有用的不变性: s[:i] + s[i:] 等于s

>>> word[:2] + word[2:]
'HelpA'
>>> word[:3] + word[3:]
'HelpA'

退化的切片索引被处理的很优美:过大的索引代替为字符串大小,下界比上界大的返回空字符串。

>>> word[1:100]
'elpA'
>>> word[10:]
''
>>> word[2:1]
''

索引可以是负数,计数从右边开始,例如:

>>> word[-1]     # The last character
'A'
>>> word[-2]     # The last-but-one character
'p'
>>> word[-2:]    # The last two characters
'pA'
>>> word[:-2]    # All but the last two characters
'Hel'

不过-0还是0,所以它不是从右边计数的!

>>> word[-0]     # (since -0 equals 0)
'H'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值