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

python 字符串操作

时间:2015-12-23 16:04:18      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:

1. 字符串连接

# join
a = [a,b,c,d]
content = ‘‘.join(a)  # ‘abcd‘

# 替换占位符
test_str = Hello %s! Welcome to %s%(Tom, our home)

# tuple 
content = %s%s%s%s%tuple(a) # abcd

# format
test_str = Hello %(name)s! Welcome to %(addr)s
d = {name:Tom, addr:our home}
test_str % d

test_str = Hello {name}! Welcome to {addr} {0}
test_str.format(^^, name=Tom, addr=our home)

2. 字符串替换

a = hello word
b = a.replace(word,python)
print b # hello python

import re
a = hello word
strinfo = re.compile(word)
b = strinfo.sub(python,a)
print b # hello python

3. 字符串反转

a = abcd
b = a[::-1]##[::-1]通过步进反转
print b

b = list(a)
b.reverse()
‘‘.join(b)

4. 编码

a = 你好
b = python
print a.decode(utf-8).encode(gbk)##decode方法把字符串转换为unicode对象,然后通过encode方法转换为指定的编码字符串对象
print b.decode(utf-8)##decode方法把字符串转换为unicode对象

5. 拆分

a=hello world
b = a.split() # [‘hello‘, ‘world‘]

 

python 字符串操作

标签:

原文地址:http://www.cnblogs.com/snow-backup/p/5069916.html

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