您的位置:首页 > 其它

(14)字符串

2016-03-03 17:47 423 查看
* 字符串常规操作
# 字符串连接
a="hello"
b="world"
c=112

>>> a+b
Out[33]: 'helloworld'

>>> "china"+a
Out[34]: 'chinahello

>>> a+`c`
Out[35]: 'hello112'
>>> a+str(c)
Out[36]: 'hello112'
>>> a+repr(c)
Out[37]: 'hello112'
数字对象的要先转化为字符对象

>>> "good %s"%a
Out[38]: 'good hello'
>>> "good %d"%c
Out[39]: 'good 112'
>>> "%s %d" %(a,c)
Out[40]: 'hello 112'
占位符连接字符串很灵活

>>> d=b
>>> d
Out[42]: 'world'
复制

>>> len(d)
Out[43]: 5
d长度为5

>>> a.upper()
Out[44]: 'HELLO'
转大写字母

>>> a.lower()
Out[45]: 'hello'
转小写字母

>>> a.capitalize()
Out[46]: 'Hello'
把各个单词首字母转为大写

>>> a.istitle()
Out[47]: False
各个单词首字母是不是大写

>>> a.isupper()
Out[48]: False
字符串是不是全是大写

>>> a.islower()
Out[49]: True
字符串是不是全是小写

>>> a
Out[50]: 'hello'
>>> a[2]='u'
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 3066, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-82-e578db6b1f79>", line 1, in <module>
a[2]='u'
TypeError: 'str' object does not support item assignment
经过上面运算后字符串本身没变
字符串是不可变的

>>> d="hello,wor ld"
>>> len(d)
Out[52]: 12
>>> d[0]
Out[53]: 'h'
>>> d[11]
Out[54]: 'd'
>>> d[-1]
Out[55]: 'd'
字符串是序列,可以采用序列的操作方法

切片操作
包含启元素,不包含结束元素 即>=,<操作
切片的参数不能为负数
>>> d[2:5]
Out[60]: 'llo'
d[2]~d[5]

>>> d[:]
Out[61]: 'hello,wor ld'
d[0]~d[len(d)]

>>> d[3:]
Out[62]: 'lo,wor ld'
d[3]~d[len(d)]

>>> d[:5]
Out[63]: 'hello'
d[0]~d[len(d)]

>>> d[1:12:2]
Out[71]: 'el,o d'
步长为2过滤

去空格操作
>>> dd=" Hello, w orld "
>>> dd.strip()
Out[75]: 'Hello, w orld'
去除左有空格

>>> dd.lstrip()
Out[76]: 'Hello, w orld '
去除左边空格数

>>> dd.rstrip()
Out[77]: ' Hello, w orld'
去除右边空格数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: