String

Python

簡介

語法

形態

控制邏輯

函數

物件

輸出入

字串處理

檔案處理

記憶體管理

lambda

影音教材

應用

科學計算

微積分

符號運算

向量運算

矩陣運算

機率統計

訊號處理

語音處理

影像處理

碎形幾何

GIS 地理資訊

自動控制

機器人

Kinect

人工智慧

自然語言

分群分類

機器學習

SVM 向量機

神經網路

最佳化

遺傳演算法

視窗程式

2D繪圖

3D繪圖

Web 程式

連結C

訊息

相關網站

參考文獻

最新修改

簡體版

English

字串範例程式

程式:str.py

import sys
def main():
    s = 'hi'
    print s[1]          ## i
    print len(s)        ## 2
    print s + ' there'  ## hi there
    pi = 3.14
    ##text = 'The value of pi is ' + pi      ## NO, does not work
    text = 'The value of pi is '  + str(pi)  ## yes
    raw = r'this\t\n and that'
    print raw     ## this\t\n and that
    multi = """It was the best of times.
    It was the worst of times."""
    print "multi=%s" % multi
    # % operator
    text = "%d little pigs come out or I'll %s and %s and %s" % (3, 'huff', 'puff', 'blow down')
    # add parens to make the long-line work:
    print "text=%s" % text
    text = ("%d little pigs come out or I'll %s and %s and %s" % 
    (3, 'huff', 'puff', 'blow down'))
    print "text=%s" % text
    # ustring = u'A unicode \u018e string \xf1'
    # print "ustring=%s" % ustring

if __name__ == '__main__':
    main()

執行結果

D:\ccc101\Python>python str.py ccc
i
2
hi there
this\t\n and that
multi=It was the best of times.
        It was the worst of times.
text=3 little pigs come out or I'll huff and puff and blow down
text=3 little pigs come out or I'll huff and puff and blow down

Unicode 字串

>>> ustring = u'A unicode \u018e string \xf1'
>>> ustring
u'A unicode \u018e string \xf1'
>>> s = unistring.encode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'unistring' is not defined
>>> s = ustring.encode('utf-8')
>>> s
'A unicode \xc6\x8e string \xc3\xb1'
>>> t = unicode(s, 'utf-8')
>>> t
u'A unicode \u018e string \xf1'
>>> t==ustring
True
>>>

參考文獻

  1. http://code.google.com/edu/languages/google-python-class/strings.html
  2. Text Processing in Python, by David Mertz — published by Addison Wesley

Facebook

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License