python 字符串特点

除了数值,Python可以操作字符串,它可以表现在以下几个方面。包含在单引号或双引号:

>>> 'spam eggs'
'spam eggs'
>>> 'doesn \' t'
"doesn't"
>>> "doesn't"
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> " \" Yes, \" he said."
'"Yes," he said.'
>>> '"Isn \' t," she said.'
'"Isn \' t," she said.'

字符串可以写多行。可以用\n表示,下一行是一个合乎逻辑的延续行,最后一个字符用反斜杠:

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

print hello

字符串可以被包围在一对三重引号里面:

print """
Usage: thingy [OPTIONS]
    -h                        Display this usage message
    -H hostname               Hostname to connect to
"""

字符串可以被连接在一起,用“+”运算符,重复*:

>>> word = 'Help' + 'A'
>>> word
'HelpA'
>>> '<' + word* 5 + '>'
'<HelpAHelpAHelpAHelpAHelpA>'

两个彼此相邻的字符串文字自动连接:

>>> 'str' 'ing'                   #  <-  This is ok
'string'
>>> 'str'.strip() + 'ing'   #  <-  This is ok
'string'
>>> 'str'.strip() 'ing'     #  <-  This is invalid
 File "<stdin>", line 1, in ?
    'str'.strip() 'ing'
                     ^
SyntaxError: invalid syntax

注意:word字符串的内容是: “HelpA”  可以是下标(索引)和C一样,字符串的第一个字符下标(索引)0。可以指定的子串切片标志来表示:两个指数由冒号分隔。

>>> word[ 4]
'A'
>>> word[ 0: 2]
'He'
>>> word[ 2: 4]
'lp'

切片索引可以使用默认值;前一个索引默认为零,第二个索引默认被切片的字符串的大小。

>>> word[: 2]     # The first two characters
'He'
>>> word[ 2:]     # Everything except the first two characters
'lpA'

和C字符串不同,Python字符串不能改变。想修改指定索引位置的字符串会导致错误:

>>> word[ 0] = 'x'
Traceback (most recent call last):
 File "<stdin>", line 1, in ?
TypeError: object doesn 't support item assignment
>>> word[: 1] = 'Splat'
Traceback (most recent call last):
 File "<stdin>", line 1, in ?
TypeError: object doesn 't support slice assignment

然而,创建一个新的字符串是简单而有效的:

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

这里是一个有用的切片操作:[:]+[:]等于。

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

指数可以是负数,从右边开始计数。例如:

>>> word[- 1]     # The last character
'A'
>>> word[- 2]     # The last-but-one character
'p'
>>> word[- 2:]     # The last two characters
'pA'
>>> word[:- 2]     # Everything except the last two characters
'Hel'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值