Python字符串,,(1)在python


(1)在python中,可以用单引号(’ ’)或者双引号(“ ”)来表示字符串,效果都是一样的,可以用‘/’来进行特殊字符的转义。

>>>‘spameggs‘#singlequotes
‘spameggs‘
>>>‘doesn\‘t‘#use\‘toescapethesinglequote...
"doesn‘t"
>>>"doesn‘t"#...orusedoublequotesinstead
"doesn‘t"
>>>‘"Yes,"hesaid.‘
‘"Yes,"hesaid.‘
>>>"\"Yes,\"hesaid."
‘"Yes,"hesaid.‘
>>>‘"Isn\‘t,"shesaid.‘
‘"Isn\‘t,"shesaid.‘

(2)如果你不想字符前面加上\将被解释为特殊字符,可以通过在第一个引号前面加上r来表示的原始字符串。

>>>print(‘C:\some\name‘)#here\nmeansnewline!
C:\some
ame
>>>print(r‘C:\some\name‘)#notetherbeforethequote
C:\some\name

(3)字符串可以跨多个行。一种方法使用三重引号:"""......"""或‘‘...‘ ‘。

>>>print("""

Usage: thingy[OPTIONS]

-h Display this usagemessage

-H hostname Hostname to connect to

""")

Usage: thingy[OPTIONS]

-h Display this usagemessage

-H hostname Hostname to connect to

(4)可以通过在字符串的行尾加上“/”来使两行变成一行。

>>>print("""

Usage: thingy[OPTIONS]\

-h Display this usagemessage

-H hostname Hostname to connect to

""")

Usage: thingy[OPTIONS] -h Display this usagemessage

-H hostname Hostname to connect to

(5)可以连接字符串(粘结在一起)+ 运算符,复制使用*:

>>>print(3 * ‘un‘ + ‘ium‘)

Unununium

(6)两个或多个字符串(即封闭引号之间的字符串)紧邻的将自动连接。

>>>‘Py‘‘thon‘
‘Python‘

但是,这仅仅适用于字符串文本之间,不适用于变量以及表达式。

>>>prefix=‘Py‘
>>>prefix‘thon‘#can‘tconcatenateavariableandastringliteral
...
SyntaxError:invalidsyntax
>>>(‘un‘*3)‘ium‘
...
SyntaxError:invalidsyntax

如果想要连接变量和字符串文本,需要使用+

>>>prefix+‘thon‘
‘Python‘

当你想要打破长字符串时,此功能是特别有用的︰

>>>text=(‘Putseveralstringswithinparentheses‘
...‘tohavethemjoinedtogether.‘)
>>>text
‘Putseveralstringswithinparenthesestohavethemjoinedtogether.‘

(7)字符串可以索引(下标),第一个字符的下标为0。Python中没有单独的字符类型;字符是大小为1的字符串︰

>>>word=‘Python‘
>>>word[0]#characterinposition0
‘P‘
>>>word[5]#characterinposition5
‘n‘

索引也可以是负数,从右边开始计数,从-1开始︰

>>>word[-1]#lastcharacter
‘n‘
>>>word[-2]#second-lastcharacter
‘o‘
>>>word[-6]
‘P‘
注意:当索引超出字符串大小时,会报错。
>>>word[42]#thewordonlyhas6characters
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
IndexError:stringindexoutofrange

(8)除了索引,还支持切片。索引用来获取单个字符,切片允许您获取子字符串︰
>>>word[0:2]#charactersfromposition0(included)to2(excluded)
‘Py‘
>>>word[2:5]#charactersfromposition2(included)to5(excluded)
‘tho‘
可以看出,切片中,开始的位置被包括,而结束的位置不包含。这样,
s[:i]+s[i:]永远等于s:

>>>word[:2]+word[2:]
‘Python‘
>>>word[:4]+word[4:]
‘Python‘

切片指数具有有用的默认值;省略的第一个索引默认为零,省略第二个索引默认为被切成字符串的大小。
>>>word[:2]#从0到2的字符
‘Py‘
>>>word[4:]#从4到结尾的字符
‘on‘
>>>word[-2:]#从-2到结尾的字符
‘on‘

不同于索引超出会报错,切片不一定会报错:
>>>word[4:42]
‘on‘
>>>word[42:]
‘‘
但是,负数索引超出的时候,切片会报错:
>>>print(word[-10,3])
Traceback(mostrecentcalllast):
File"<pyshell#39>",line1,in<module>
print(word[-10,3])
TypeError:stringindicesmustbeintegers

(9)python中字符串是不可变的,所以不能使用索引或者切片对字符串进行改变。
>>>word[0]=‘J‘
...
TypeError:‘str‘objectdoesnotsupportitemassignment
>>>word[2:]=‘py‘
...
TypeError:‘str‘objectdoesnotsupportitemassignment
如果你需要一个新字符串,你需要重新建一个字符串
>>>‘J‘+word[1:]
‘Jython‘
>>>word[:2]+‘py‘
‘Pypy‘
(10)内建函数len()返回字符串的长度
>>>s=‘supercalifragilisticexpialidocious‘
>>>len(s)
34

当然,字符串还有很多其他的性质和方法,以后会继续讲解。


Python字符串

评论关闭