码迷,mamicode.com
首页 > 编程语言 > 详细

Python字符串

时间:2017-02-20 23:24:37      阅读:281      评论:0      收藏:0      [点我收藏+]

标签:python   字符串   切片   

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

 

>>> ‘spam eggs‘  # single quotes
‘spam eggs‘
>>> ‘doesn\‘t‘  # use \‘ to escape the single quote...
"doesn‘t"
>>> "doesn‘t"  # ...or use double quotes instead
"doesn‘t"
>>> ‘"Yes," he said.‘
‘"Yes," he said.‘
>>> "\"Yes,\" he said."
‘"Yes," he said.‘
>>> ‘"Isn\‘t," she said.‘
‘"Isn\‘t," she said.‘

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

>>> print(‘C:\some\name‘)  # here \n means newline!
C:\some
ame
>>> print(r‘C:\some\name‘)  # note the r before the quote
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‘t concatenate a variable and a string literal
  ...
SyntaxError: invalid syntax
>>> (‘un‘ * 3) ‘ium‘
  ...
SyntaxError: invalid syntax

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

>>> prefix + ‘thon‘
‘Python‘

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

>>> text = (‘Put several strings within parentheses ‘
...         ‘to have them joined together.‘)
>>> text
‘Put several strings within parentheses to have them joined together.‘

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

>>> word = ‘Python‘
>>> word[0]  # character in position 0
‘P‘
>>> word[5]  # character in position 5
‘n‘

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

>>> word[-1]  # last character
‘n‘
>>> word[-2]  # second-last character
‘o‘
>>> word[-6]
‘P‘
注意:当索引超出字符串大小时,会报错。
>>> word[42]  # the word only has 6 characters
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
 
(8)除了索引,还支持切片。索引用来获取单个字符,切片允许您获取子字符串︰
>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
‘Py‘
>>> word[2:5]  # characters from position 2 (included) to 5 (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 (most recent call last):
  File "<pyshell#39>", line 1, in <module>
    print(word[-10,3])
TypeError: string indices must be integers
 
(9)python中字符串是不可变的,所以不能使用索引或者切片对字符串进行改变。
>>> word[0] = ‘J‘
  ...
TypeError: ‘str‘ object does not support item assignment
>>> word[2:] = ‘py‘
  ...
TypeError: ‘str‘ object does not support item assignment
如果你需要一个新字符串,你需要重新建一个字符串
>>> ‘J‘ + word[1:]
‘Jython‘
>>> word[:2] + ‘py‘
‘Pypy‘
(10)内建函数len()返回字符串的长度
>>> s = ‘supercalifragilisticexpialidocious‘
>>> len(s)
34
 
当然,字符串还有很多其他的性质和方法,以后会继续讲解。
 


Python字符串

标签:python   字符串   切片   

原文地址:http://itlearninger.blog.51cto.com/12572641/1899566

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!