1. 程式人生 > >Python基礎(二)之數據類型和運算(2)——字符串

Python基礎(二)之數據類型和運算(2)——字符串

創建 options 生成 quotes 字符串 表達 ngs 字符串格式化 lib

字符串基礎

Python 也提供了可以通過幾種不同方式表示的字符串。它們可以用單引號 (‘...‘) 或雙引號 ("...") 標識 。\ 可以用來轉義引號:

>>> spam eggs  # single quotes
spam eggs
>>> doesn\‘t  # use \‘ to escape the single quote...
"doesn‘t"
>>> "doesn‘t"  # ...or use double quotes instead
"doesn‘t"
>>> "Yes," he said.
"Yes," he said. >>> "\"Yes,\" he said." "Yes," he said. >>> "Isn\‘t," she said. "Isn\‘t," she said.

在交互式解釋器中,輸出的字符串會用引號引起來,特殊字符會用反斜杠轉義。雖然可能和輸入看上去不太一樣,但是兩個字符串是相等的。如果字符串中只有單引號而沒有雙引號,就用雙引號引用,否則用單引號引用。print() 函數生成可讀性更好的輸出, 它會省去引號並且打印出轉義後的特殊字符:

>>> "Isn\‘t," she said.
"Isn\‘t," she said. >>> print("Isn\‘t," she said.) "Isn‘t," she said. >>> s = First line.\nSecond line. # \n means newline >>> s # without print(), \n is included in the output First line.\nSecond line. >>> print(s) # with print(), \n produces a new line
First line. Second line.

如果你前面帶有 \ 的字符被當作特殊字符,你可以使用 原始字符串,方法是在第一個引號前面加上一個 r:

>>> print(C:\some\name)  # here \n means newline!
C:\some
ame
>>> print(rC:\some\name)  # note the r before the quote
C:\some\name

字符串多行輸出

字符串文本能夠分成多行。一種方法是使用三引號:"""...""" 或者 ‘‘‘...‘‘‘。行尾換行符會被自動包含到字符串中,但是可以在行尾加上 \ 來避免這個行為。下面的示例: 可以使用反斜杠為行結尾的連續字符串,它表示下一行在邏輯上是本行的後續內容:

1 print("""2 Usage: thingy [OPTIONS]
3      -h                        Display this usage message
4      -H hostname               Hostname to connect to
5 """)

將生成以下輸出(註意,沒有開始的第一行):

Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to

字符串格式化輸出

萬惡的字符串拼接   python中的字符串在C語言中體現為是一個字符數組,每次創建字符串時候需要在內存中開辟一塊連續的空,並且一旦需要修改字符串的話,就需要再次開辟空間,萬惡的+號每出現一次就會在內從中重新開辟一塊空間。

字符串可以由 + 操作符連接(粘到一起),可以由 * 表示重復:

>>> # 3 times ‘un‘, followed by ‘ium‘
>>> 3 * un + ium
unununium

相鄰的兩個字符串文本自動連接在一起。:

>>> Py thon
Python

它只用於兩個字符串文本,不能用於字符串表達式:

>>> prefix = Py
>>> prefix thon  # can‘t concatenate a variable and a string literal
  ...
SyntaxError: invalid syntax
>>> (un * 3) ium
  ...
SyntaxError: invalid syntax

如果你想連接多個變量或者連接一個變量和一個字符串文本,使用 +:

>>> prefix + thon
Python

這個功能在你想切分很長的字符串的時候特別有用:

>>> text = (Put several strings within parentheses 
            to have them joined together.)
>>> text
Put several strings within parentheses to have them joined together.

字符串拼接格式化輸出

name = input("name:")
age = input("age:")
job = input("job:")

print("""
-------------info-----------
name:"""+name+"""
age:"""+age+"""
job:"""+job)

輸入

name:Brain
age:23
job:IT

輸出

-------------info-----------
name:Brain
age:23
job:IT

Python基礎(二)之數據類型和運算(2)——字符串