字符串是由字符組成的一串字符序列,字符串是有順序的,從左到右,索引從0開始,依次遞增。python
Python中字符串類型:str。shell
Python中字符串的三種表示方式:函數
(1)普通字符串:採用單引號(')或雙引號(")括起來的字符串。編碼
(2)原始字符串(raw string):在普通字符串的前面加 r,字符串中的特殊字符不須要轉義。spa
(3)長字符串:字符串中包含換行、縮進等排版字符,使用三重單引號(''')或三重雙引號(""")括起來的字符串。code
Python中字符串採用Unicode編碼。orm
>>> s='Hello World!' >>> s 'Hello World!'
轉義字符:對象
轉義字符 | 描述 |
---|---|
\(在行尾時) | 換行 |
\t | 水平製表符 |
\n | 換行 |
\r | 回車 |
\" | 雙引號 |
\' | 單引號 |
>>> s='Hello\tWorld!' >>> print(s) Hello World!
原始字符串:在普通字符串前面加 r。原始字符串能夠直接按照字符串使用,沒有轉義符。blog
>>> s=r'Hello\tWorld!' >>> print(s) Hello\tWorld!
長字符串能夠包含換行、縮進等排版字符。索引
>>> s='''Hello ... World!''' >>> print(s) Hello World!
Python提供3種字符串格式化方法:
(1)%運算符
(2)內置函數format()
(3)建立字符串對象配合format(),使用{}進行替換
語法:
%[flag][width][.precision]
其中,%:標記轉換說明符開始
flag:轉換標記
width:最小寬度,轉換後的值所保留的最小字符個數。若是是*,則寬度從值元組中讀取。
precision:精度,若是轉換的實數,精度表示出如今小數點後的位數;若是轉換的是字符串,則表示最大寬度。若是是*,則精度從值元組中讀取。
寬度和精度都是整數,經過點號(.)分隔。兩個都是可選參數,若是給出精度,則必須包含點號。
轉換類型:
符號 | 描述 | 符號 | 描述 |
---|---|---|---|
%c | 格式化字符及其ASCII碼 | %s | 格式化字符串 |
%d | 格式化整型 | %u | 格式化無符號整型 |
%o | 格式化無符號八進制數 | %x,%X | 格式化無符號十六進制 |
%f | 格式化浮點數字,可指定精度值 | %e,%E | 用科學計數法格式化浮點數 |
%g,%G | %f和%e的簡寫,十進制整數或浮點數。 | %% | 輸出數據時顯式百分號 |
%r | 使用repr()函數輸出 |
轉換標誌(flag):
符號 | 描述 | 符號 | 描述 |
---|---|---|---|
'#' | 十6、八進制進行轉換時,可在前方補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位小數、長度爲十、位數不足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'
>>> '{:,}'.format(10000) # 千分位 '10,000'
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
join()方法:用於將序列中的元素以指定字符鏈接成一個新的字符串。
join()語法:
str.join(seq)
其中,str:指定字符
seq:待鏈接的元素序列
返回結果:指定字符鏈接序列中元素後生成的新字符串
>>> dirs = ['','usr','bin','python3'] >>> mark = '/' >>> mark.join(dirs) '/usr/bin/python3'
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'
數字轉換字符串有不少方法,另外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'