1. 程式人生 > >Python基礎:數據類型-字符串(7)

Python基礎:數據類型-字符串(7)

位置 for ase arguments value 千分位 nts ont mat

1.字符串基本操作

  字符串是由字符組成的一串字符序列,字符串是有順序的,從左到右,索引從0開始,依次遞增。

  Python中字符串類型:str。

  Python中字符串的三種表示方式:

  (1)普通字符串:采用單引號(‘)或雙引號(")括起來的字符串。

  (2)原始字符串(raw string):在普通字符串的前面加 r,字符串中的特殊字符不需要轉義。

  (3)長字符串:字符串中包含換行、縮進等排版字符,使用三重單引號(‘‘‘)或三重雙引號(""")括起來的字符串。

1.1 普通字符串

  Python中字符串采用Unicode編碼。

>>> s=
Hello World! >>> s Hello World!

  轉義字符:

轉義字符描述
\(在行尾時) 換行
\t 水平制表符
\n 換行
\r 回車
\" 雙引號
\‘ 單引號
>>> s=Hello\tWorld!
>>> print(s)
Hello   World!

1.2 原始字符串

  原始字符串:在普通字符串前面加 r。原始字符串可以直接按照字符串使用,沒有轉義符。

>>> s=r
Hello\tWorld! >>> print(s) Hello\tWorld!

1.3 長字符串

  長字符串可以包含換行、縮進等排版字符。

>>> s=‘‘‘Hello
...  World!‘‘‘
>>> print(s)
Hello
 World!

2.字符串格式化

  Python提供3種字符串格式化方法:

  (1)%運算符

  (2)內置函數format()

  (3)創建字符串對象配合format(),使用{}進行替換

2.1 %運算符 — 格式字符串

  語法:

%[flag][width][.precision]

  其中,%:標記轉換說明符開始

     flag:轉換標記

     width:最小寬度,轉換後的值所保留的最小字符個數。如果是*,則寬度從值元組中讀取。

     precision:精度,如果轉換的實數,精度表示出現在小數點後的位數;如果轉換的是字符串,則表示最大寬度。如果是*,則精度從值元組中讀取。

  寬度和精度都是整數,通過點號(.)分隔。兩個都是可選參數,如果給出精度,則必須包含點號。

  轉換類型:

符號描述符號描述
%c 格式化字符及其ASCII碼 %s 格式化字符串
%d 格式化整型 %u 格式化無符號整型
%o 格式化無符號八進制數 %x,%X 格式化無符號十六進制
%f 格式化浮點數字,可指定精度值 %e,%E 用科學計數法格式化浮點數
%g,%G %f和%e的簡寫,十進制整數或浮點數。 %% 輸出數據時顯式百分號
%r 使用repr()函數輸出

  轉換標誌(flag):

符號描述符號描述
‘#‘ 十六、八進制進行轉換時,可在前方補0。 ‘0‘ 數值前補0
‘-‘ 靠左對齊,若與0同時使用,會優先於0。 ‘‘ 保留一個空格
> 靠右對齊 < 靠左對齊
+ 在轉換值前加正負號
>>> %c%97 # ASCII碼輸出字符
a
>>> 年同比變化:%.2f%%%120.987 # 輸出百分號
年同比變化:120.99%
>>> %o%10 # 轉換八進制數
12
>>> %#o%10 # 轉換補0八進制數
0o12
>>> %x%127 # 轉換十六進制數
7f
>>> %#x%127 # 轉換補0十六進制數
0x7f
>>> from math import pi
>>> %010.5f%pi # pi轉換:帶5位小數、長度為10、位數不足0填充的字符串
0003.14159
>>> s = %-10.5f%pi # 左對齊
>>> s
3.14159   
>>> len(s)
10
>>> s = %-010.5f%pi # -優先於0
>>> s
3.14159   
>>> %10.5f%pi # 空格填充
   3.14159
>>> %-+10.5f%pi # 左對齊顯示正負符號
+3.14159  
>>> %+-10.5f%pi # 左對齊顯示正負符號
+3.14159  
>>> %-+10.5f%-pi # 左對齊顯示正負符號
-3.14159  
>>> %3.5f%pi #最小寬度 < 實際寬度,顯示實際寬度
3.14159
>>> %.5s%(Hello World) # 字符串精度值:最大寬度
Hello
>>> s = %10.5s%(Hello World) # 字符串截取最大寬度後空格填充
>>> s
     Hello
>>> len(s)
10
>>> %.*s%(5,Hello World) # 精度從元組中讀取
Hello
>>> %*.*s%(10,5,Hello World) # 寬度、精度從元組中讀取
     Hello

2.2 內置函數format()

>>> {:,}.format(10000) # 千分位
10,000

3.字符串方法

3.1 find()方法

  find()方法:用於檢測字符串中是否包含子字符串sub。如果指定start(開始)和end(結束),則在指定範圍內檢測。

        如果包含子字符串,返回開始的索引;否則返回-1。

  find()語法:

str.find(sub[, start[, end]])

  其中,sub:指定檢測的子字符串,

     start:開始索引,默認為0;

     end:結束索引,默認為字符串的長度。

  返回結果為子字符串所在位置的最左端索引,如果沒有找到,則返回-1。

  help查看find()方法定義:

>>> help(str.find)
Help on method_descriptor:

find(...)
    S.find(sub[, start[, end]]) -> int
    
    Return the lowest index in S where substring sub is found,
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.
    
    Return -1 on failure.

  rfind()方法:與find()方法類似,區別是找到返回最右端位置的索引。

>>> help(str.rfind)
Help on method_descriptor:

rfind(...)
    S.rfind(sub[, start[, end]]) -> int
    
    Return the highest index in S where substring sub is found,
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.
    
    Return -1 on failure.
>>> field = Hello World
>>> field.find(o)
4
>>> field.rfind(o)
7
>>> field.find(o,5) # 指定開始索引    
7
>>> field.find(a) # 未找到則返回-1        
-1
>>> words = ‘Where there is a will,there is a way.‘
>>> len(words)
37
>>> words.find(‘is‘)
12
>>> words.rfind(‘is‘)
28

技術分享圖片

3.2 join()方法

  join()方法:用於將序列中的元素以指定字符連接成一個新的字符串。

  join()語法:

str.join(seq)

  其中,str:指定字符

     seq:待連接的元素序列

     返回結果:指定字符連接序列中元素後生成的新字符串

>>> dirs = [‘‘,usr,bin,python3]
>>> mark = /
>>> mark.join(dirs)
/usr/bin/python3

4.字符串與數字相互轉換

4.1 字符串轉換數字

  int()或float():字符串轉換數字,如果轉換成功,則返回數字;否則引發異常。

>>> int(‘9‘)
9
>>> int(‘9.6‘)
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    int(‘9.6‘)
ValueError: invalid literal for int() with base 10: ‘9.6‘
>>> float(‘9.6‘)
9.6

  默認情況下int()函數都將字符串參數作為十進制數字進行轉換,可以指定基數(進制)。

>>> int(‘a‘)
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    int(‘a‘)
ValueError: invalid literal for int() with base 10: ‘a‘
>>> int(‘a‘,16)
10
>>> int(‘ab‘,16)
171
>>> int(‘h‘,16)
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    int(‘h‘,16)
ValueError: invalid literal for int() with base 16: ‘h‘

4.2 數字轉換字符串

  數字轉換字符串有很多方法,另外Python中字符串提供str()函數。

>>> str(9.6)
‘9.6‘
>>> str(True)
‘True‘
>>> str([1,2,3])
‘[1, 2, 3]‘

  str()函數所有類型都可以轉換,但缺點是不能格式化。如果格式化字符串可以使用format()函數。

>>> from math import pi
>>> {:.2f}.format(pi)
3.14

Python基礎:數據類型-字符串(7)