python文字列操作
6632 ワード
1.文字列接続
2.文字列置換
3.文字列の反転
4.コード化
5.分割
# 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']