码迷,mamicode.com
首页 > 其他好文 > 详细

第十八讲 字符串基本操作

时间:2015-03-17 02:07:29      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:python 学习

eg1:open(‘c:\temp\tex.t‘,‘a+‘)报错:因为没有加r,\t会被当做转义字符(制表符)

改进如下:

    open(‘c:\\temp\\tex.t‘,‘a+‘) 或者------两个斜杠

    open(r‘c:\temp\tex.t‘,‘a+‘)------------r代表原始字符串,关闭转义机制

字符串的基本操作

1, + 连接

2, * 重复

3, s[i] 索引index

4, s[i:j] 切片slice

5, for循环遍历

###############

1,连接  +  前后连个对象必须都是字符串(如果是其他类型,需要转换)

eg1:

>>> s1="www.baidu.com"
>>> s2="ronbin"
>>> print s1,s2
www.baidu.com ronbin---------逗号,在同一行输出,但是之间有空格
>>> s3=s1+s2
>>> print s3
www.baidu.comronbin----------完整连接

eg2:

>>> i=12
>>> s1="times"
>>> print i+s1--------------类型不同无法直接连接
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: ‘int‘ and ‘str‘
>>> print str(i)+s1
12times
>>> print str(i)+‘ ‘+s1
12 times


2,重复  *

eg1:

>>> list1=[1]*5
>>> list1
[1, 1, 1, 1, 1]
>>> list2=[1,‘3‘,67.09]*3-------相当于3个列表做的连接(将列表扩大了3倍)   
>>> list2
[1, ‘3‘, 67.09, 1, ‘3‘, 67.09, 1, ‘3‘, 67.09]

eg1:

>>> s=‘a‘
>>> s1=s+s+s+s
>>> s1
‘aaaa‘

>>> s1=s*4
>>> s1
‘aaaa‘
>>> s1=‘a‘*4
>>> s1
‘aaaa‘

当需要连接的字符串相同时, * <======> n个+

3,索引

>>> s2=‘abcdefd‘
>>> ch=s2[3]----------[3]被称之为索引index
>>> ch
‘d‘

方法:string_name[index]

4,切片

方法:string_name[start_index:stop_index]

start_index:要取字符串的首字母的index      

stop_index:要取字符串的尾字母的index+1

eg1:

>>> s2=‘abcdefd‘
>>> sub=s2[1:5]
>>> sub
‘bcde‘

start_index省略,则从开始切

>>> sub=s2[:5]
>>> sub
‘abcde‘

stop_index省略,则切到最后

>>> sub=s2[1:]
>>> sub
‘bcdefd‘

start_index和stop_index都省略,则全切(又相当于没切)

>>> sub=s2[:]
>>> sub
‘abcdefd‘

start_index和stop_index可以是负数

-1代表最后一位,-2代表倒数第二位,以此类推


第十八讲 字符串基本操作

标签:python 学习

原文地址:http://tenderrain.blog.51cto.com/9202912/1621297

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