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

python【二】python的字符串操作

时间:2014-11-04 15:04:07      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:style   ar   使用   sp   strong   on   bs   size   python   

python的字符串操作很灵活;先来看一个例子:

str=‘helloworld‘

首先我们输出这个字符串:

print  str这是一种表示方法,还有很多表示的方法;

比如:

print  str[0:10]

我们也能得到 helloworld

print str[1:3]

我们得到:el,截取字符串的el两个字符;

 

截取字符串的前提条件:

是这样的我们如果要截取某段字符,首先要查找到这段字符的起始位置,然后才能正确截取;在python中提供了字符串查找的方法,这个跟c语言里面的字符查找很相似;即find()方法;

比如我们来查找wo这个字符串;

poN =str.find(‘wo‘)

我们将得到5,即wo得首个字符在字符串的5号位置出现。这样我们从5号位置截取2个长度的字符就可以的到我们想要的wo字符串

了;

5:7表示截取字符串的长度;为2

print  str[5:7] 结果就是wo

 

python关于字符串的另类操作:

 

比如我们要输出上述字符串的最后一个字符,只需要进行以下操作就可以了:
print  str[-1]  或者print str[10]这个需要知道字符串的长度才可以;

我们将得到  d这个字符;

我们还可以得到除最后一个字符以外的所有字符:
print  str[:-1]我们得到  helloworl;

 

python中字符串的拼接:

 

当然操作字符串拼接和替换的前提是都要找到该字符串即要使用 str.find()函数;

怎么拼接呢?在python中可以使用 +号操作符来进行字符串间的拼接

 

比如:

str1=‘we  are‘

str2=‘good  friends‘

str3=str1+‘ ‘+str2 

print  str3    

我们得到we  are  good   friends

 

python字符串的不可变性:

字符串在python中具有不可变性--在字符串创建后,其内部的值不能改变,这个和c/c++对字符串的操作变化要大的多;

那么我们怎样来改变其内部的值呢?
还是上面的那个helloworld,我想让他变成hellozorld字符串,这个怎么实现?

我们可以这么做:

str=‘helloworld‘

str1=‘z‘

str2=str[0:5]+str1

str3=str[6:]

str4=str2+str3

print  str4

我们得到  hellozorld

 

python中的字符替换

像我们上面做的那样,我并没有使用python提供的替换函数,实际上python是有提供替换函数的,就是replace()方法

比如:

str=‘helloworld‘

str2=str[1:5]

str3=‘call‘

str4=str.replace(str2,str3)

print str4

我们得到 hcallworld ,这个替换方法是有一个返回值的,原因是字符串内部不能改变。

 

Python中获取字符串的长度:

print  len(str)

 

python中字符串的大小写转换;

 

str=‘helloworld‘

print str.upper()

我们将得到HELLOWORLD

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

python【二】python的字符串操作

标签:style   ar   使用   sp   strong   on   bs   size   python   

原文地址:http://blog.csdn.net/u010296979/article/details/40783295

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