python 進階學習之10

運行時刻字符串連接

>>> '%s %s' % ('spa','oil')

'spa oil'

>>> s=' ' .join(('ss','ww','21'))
>>> s
'ss ww 21'

編譯時字符串連接

>>> foo='hello'"world"
>>> foo
'helloworld'
通過這種方法,你可以把長的字符串分成幾部分來寫,而不用加反斜槓

普通字符串轉化爲Unicode 字符串

如果把一個普通字符串和一個Unicode 字符串做連接處理,Python 會在連接操作前先把普通字符串轉化爲Unicode 字符串
>>> 'he'+u' '+'won'+u'!'
u'he won!'

只適用於字符串的操作符

格式化操作符( % )
調試工具 repr(),str()或``

字符串模板

Template 對象有兩個方法,substitute()和safe_substitute().前者更爲嚴謹,在key 缺少的情況下它會報一個KeyError 的異常出來,而後者在缺少key 時,直接原封不動的把字符串顯示出來.
>>> from string import Template
>>> s=Template('are ${many}${lang}symbols')
>>> print s.substitute(lang='Python',many=3)
are 3Pythonsymbols
>>> print s.substitute(lang='Python')       
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/usr/lib64/python2.4/string.py", line 172, in substitute
    return self.pattern.sub(convert, self.template)
  File "/usr/lib64/python2.4/string.py", line 162, in convert
    val = mapping[named]
KeyError: 'many'
>>> print s.safe_substitute(lang='Python')
are ${many}Pythonsymbols

原始字符串操作符( r/R )

在原始字符串裏,所有的字符都是直接按照字面的意思來使用,沒有轉義特殊或不能打印的字符。
這個'r'可以是小寫也可以是大寫,唯一的要求是必須緊靠在第一個引號前.
>>> '\n'
'\n'
>>> print '\n'

>>> r'\n'
'\\n'
>>> print r'\n'
\n

Unicode 字符串操作符( u/U )

>>> u'abc'
u'abc'

內建函數

cmp()
序列類型函數
len()
max() and min()
enumerate()
>>> s='fool'
>>> for i,t in enumerate(s):
...   print i,t
... 
0 f
1 o
2 o
3 l
zip()
>>> s,t = 'foa','wer'
>>> zip(s,t)
[('f', 'w'), ('o', 'e'), ('a', 'r')]
字符串類型函數
raw_input()
str() and unicode()
chr(), unichr(), and ord()
字符串不變性

Unicode

是用來在多種雙字節字符的格式、編碼進行轉換的,其中包括一些對這類字符串的操作管理功能中最著名的是UTF-8 編碼,它也用一個字節來編碼ASCII 字符,這讓那些必須同時處理ASCII碼和Unicode 碼文本的程序員的工作變得非常輕鬆,因爲ASCII 字符的UTF-8 編碼跟ASCII 編碼完全相同。
Unicode 支持多種編碼格式,這爲程序員帶來了額外的負擔,每當你向一個文件寫入字符串的時候,你必須定義一個編碼(encoding 參數)用於把對應的Unicode 內容轉換成你定義的格式,Python 通過Unicode 字符串的encode()函數解決了這個問題,該函數接受字符串中的字符爲參數,輸出你指定的編碼格式的內容。

#!/usr/bin/python
CODEC='utf-8'
FILE='unicode.txt'
hello_out=u"hello world\n"
bytes_out=hello_out.encode(CODEC)
f=open(FILE,"w")
f.write(bytes_out)
f.close()
f=open(FILE,"r")
bytes_in=f.read()
f.close()
hello_in=bytes_in.decode(CODEC)
print hello_in,
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章