随笔 - 224  文章 - 41  trackbacks - 0
<2013年5月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

享受编程

常用链接

留言簿(11)

随笔分类(159)

随笔档案(224)

文章分类(2)

文章档案(4)

经典c++博客

搜索

  •  

最新评论

阅读排行榜

评论排行榜


python中字符串操作--截取,查找,替换
    python中,对字符串的操作是最常见的,python对字符串操作有自己特殊的处理方式。
字符串的截取
python中对于字符串的索引是比较特别的,来感受一下:
字符串的查找
查找当前字符串中,是否包含另外的字符串。
我们可以使用 index,或者find来进行查找,find和index的区别是,如果使用的是index的话,字符串查找中,如果找不到相应的字符串,会抛出一个ValueError的异常。
s = '123456789'
s.index('23')
#输出:1
s.find('23')
#输出:1
s.index('s')
#输出
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
s.find('s')
#输出 -1


分割字符串
总是有很多特殊字符,可以用来分割字符串。数据库中经常把一组照片放在一个字段中,比如
img1.jpg@@@img2.jpg@@@img3.jpg
需要把不定长的照片都取出来,就需要同特殊字符把字符串分开,得到不同的照片。
分割的命令为split
s = 'img1.jpg@@@img2.jpg@@@img3.jpg'
s.split('@@@')
#结果为一个数值:['img1.jpg', 'img2.jpg', 'img3.jpg']
</code></pre>
### 字符串格式化
Python 支持格式化字符串的输出 。尽管这样可能会用到非常复杂的表达式,但最基本的用法是将一个值插入到一个有字符串格式符 %s 的字符串中。
在 Python 中,字符串格式化使用与 C 中 sprintf 函数一样的语法。
<pre><code>
#!/usr/bin/python
print "My name is %s and weight is %d kg!" % ('Zara', 21) 
#以上实例输出结果: My name is Zara and weight is 21 kg!

字符串Template化
在python中Template可以将字符串的格式固定下来,重复利用。
Template属于string中的一个类,要使用他的话可以用以下方式调用:
from string import Template
我们使用以下代码:
>>> s = Template('There  ${moneyType} is  ${money}')
>>> print s.substitute(moneyType = 'Dollar',money=12)
运行结果显示“There  Dollar is  12”
这样我们就可以替换其中的数据了。
更多入门教程可以参考:[http://www.bugingcode.com/python_start/] (http://www.bugingcode.com/python_start/)


posted on 2018-01-12 16:04 漂漂 阅读(188) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理