您的位置:首页 > 编程语言 > Python开发

python 字符串操作

2015-12-23 14:41 671 查看
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']
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: