一基礎: 1.1字符串拼接 「Hello」 + 「 world!」 =》 「Hello world!」 x = 「Hello」, y = 「 world!」 x + y =》 「Hello world!」 1.2字符串表示(str和repr): 使用python直接輸出的字符串是用單引號表示的python類型值: 「Hello world!」 =》 ‘Hello world!’//表示該對象未字符串對象 1000L =》 1000L//表示該值爲長整型 使用print函數輸出字符串能夠獲得字符串值 print 「Hello world!」 =》Hello world! print 1000L =》 1000 1.2.1str類型 如:print str("Hello world!") => Hello World! print str(1000L) => 1000L str([object]) 返回一個能夠用來表示對象的可打印的友好的字符串 對字符串,返回自己。 沒有參數,則返回空字符串 對類,可經過 __str__() 成員控制其行爲。該成員不存在,則使用其 __repr__() 成員。 與 repr 區別:不老是嘗試生成一個傳給 eval 的字符串,其目標是可打印字符串。 Python 手冊: Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. If no argument is given, returns the empty string, . 1.2.2repr函數 如:print repr(「Hello world!」) =》 ‘Hello world!’ print repr(1000L) =》 1000L repr(object) 返回一個能夠用來表示對象的可打印字符串 首先,嘗試生成這樣一個字符串,將其傳給 eval()可從新生成一樣的對象 不然,生成用尖括號包住的字符串,包含類型名和額外的信息(好比地址) 一個類(class)能夠經過 __repr__() 成員來控制repr()函數做用在其實例上時的行爲。 Python 手冊: Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a repr() method. 注:str和repr都是轉換爲字符串,str是友好的,repr則是表示python類型的字符串。str是類型,repr是 函數。 1.3 input和raw_input input([prompt]) 等同於 eval(raw_input(prompt)). 注意:input的輸入要求是一個有效的python表達式. 如: input(「Name :」) 若是再Name :後直接輸入字符串內容 Tom是錯誤的。由於它不是有效的python表達式。 應該輸入「Tom」 可是使用raw_input()則不會有此問題,它會將輸入當作原始數據放入字符串中。 如:raw_input("Number :") Number : 13 =>'13'//表示字符串13 1.4 字符串換行 若是須要很長的字符串(或表達式),能夠使用\換行。 對於長字符串能夠使用三個單引號('''......'''),或三個雙引號("""......""")表示,而不用使用\換行,並 且長字符串中的單引號或雙引號字符不用再轉義。 1.5 原始字符串 以r開頭的字符串爲原始字符串,如:r‘Hello world!’ 注意:原始字符串中的任何字符都會保持原始字符形式,不會處理轉義字符。 如 print r‘Hello \nworld’ =》Hello \nworld 原始字符串不能已反斜槓\結尾,若是要結尾輸出反斜槓,則以字符串拼接實現,+‘\\’。 1.6 unicode字符串 python3.0中字符串都爲unicode字符串,以u開頭。 u‘Hello World!’ =》u‘Hello World!’