簡單講解Python中的字串與字串的輸入輸出

2022-10-04 22:03:31 字數 1961 閱讀 9598

字串www.cppcns.com

字串用''或者""括起來,如果字串內部有『或者",需要使用\進行轉義

>>> print 'i\'m ok.'

i'm ok.

轉義字元\可以轉義很多字元,比如\n表示換行,\t表示製表符,字元\本身也要轉義,所以\\表示的字元就是\。當然如果不需要轉義,可以使用r'':

>>> print '\\\t\\'

\ \

>>> print r'\\\t\\'

\\\t\\

如果字串內部有很多換行,用\n寫在一行裡不好閱讀,為了簡化,python允許用'''…'''的格式表示多行內容:

>>> print '''line1

... line2

... line3'''

line1

line2

line3

如果寫成程式,就是:

print '''line1

line2

line3'''

可能出現的問題

中文編碼問題

# coding = utf-8

結果報錯:

syntaxerror: non-ascii character 『/xe6'

所以最後改成了

# coding=utf-8

唉....

unicode編碼問題

python 2.7.6 (default, mar 22 2014, 22:59:56)

[gcc 4.8.2] on linux2

type "help", "copyright", "credits" or "license" for more information.

>>> len('中文')

6>>> len(u'中文')

2>>>

注意: 這個問題是由python編碼導致的,詳細的編碼問題詳見字串和編碼,但是在python 3.x中這個編碼問題就不存在了:

python 3.4.0 (defwww.cppcns.comault, jun 19 2015, 14:20:21)

[gcc 4.8.2] on linux

type "help", "copyright", "credits" or "license" for more information.

>>> len('中文')

2>>> len(u'中文')

2>>>

輸出>>& print 'hello, world'

hello, world

>>> print 'the quick brown fox', 'jumps over', 'the lazy dog'

the quick brown fox jumps over the lazy dog

>>> print '100 + 200 =', 100 + 200

100 + 200 = 300

輸入>>> name = raw_input()

michael

>>> name

'michael'

>>> print name

michael

>>> name = raw_input('please enter your name: ')

please enter your name:

注意: raw_input返回的永遠是字串,也就是說你輸入乙個int型,返回的是乙個數字字串,你需要進行轉換:

>>> number = raw_input("輸入乙個整數:")

輸入乙個整數:123

>>> number

'123'

>>www.cppcns.com;> number = int(raw_input("輸入乙個整數:"))

輸入一程式設計客棧個整數:123

>>> number

123本文標題: 簡單講解python中的字串與字串的輸入輸出

本文位址:

Python中list 字典 字串的講解

python 的list講解 計算機中的陣列是從0開始的 list中的下標 角標 索引說的都是乙個 陣列都是從0開始的。stus 劉 王 張 stus2 空的列表 stu3 list print stus 這樣列印出來的就是stus 劉愛俠 王小二 張小三 李四 print stus 0 會列印出列...

Python 字串簡單使用

resume hello world print resume hello worldresume name 高雷 company xx企業 age 18 print resume name 高雷 company xx企業 age 18resume hello world print resume ...

python中的字串

方法1 用字串的join方法 a a b c d content content join a print content 方法2 用字串的替換佔位符替換 a a b c d content content s s s s tuple a print content 我們可以通過索引來提取想要獲取的...