python基础 1: string

字符串

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:
 |  
...



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值