字符串
python直接支持字符串操作,字符串可以是单引号、双引号、三引号括起来的串。前两者没有区别,三引号则是支持多行的。
string是不可变的,也就是说如果对一个变量重新赋值,那么会新创建一个string对象,并且把变量绑定上去,而原先的对象则可能会被回收。
下面举例展示string的一些基本操作:
>>> s='abc'
>>> s[0]
'a' #string的index也是从0开始
>>> s[3]
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
s[3]
IndexError: string index out of range
>>> s[-1]
'c'
>>> s[-3]
'a'
>>> s[-4]
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
s[-4]
IndexError: string index out of range
>>> s[:]
'abc'
>>> s[1:]
'bc'
>>> s[:1]
'a'
>>> s[-1:]
'c'
>>> s[:-1]
'ab'
>>>
>>> s+'de'
'abcde'
>>> s
'abc' #immutable
>>> s*2
'abcabc'
>>>
>>> s.find('c')
2
>>> s.replace('c','d')
'abd'
>>> s
'abc' #immutable
>>> '.'.join(s)
'a.b.c'
>>> '.'.join(s).split('.')
['a', 'b', 'c']
help(str)就可以获得所有string的操作:
>>> help(str)
Help on class str in module __builtin__:
class str(basestring)
| str(object='') -> string
|
| Return a nice string representation of the object.
| If the argument is a string, the return value is the same object.
|
| Method resolution order:
| str
| basestring
| object
|
| Methods defined here:
|
...
本文介绍了Python中字符串的基本操作,包括索引、切片、连接、重复等,并演示了如何使用find和replace方法来查找和替换字符。此外还展示了字符串的不可变特性以及字符串分割和拼接的方法。
5879

被折叠的 条评论
为什么被折叠?



