Python3中的字符串

1:字符串的定義
         把字符連成串,在Python中使用', ",''',"""引起來的內容被稱爲字符串。
         在Python中字符串是一種不可變數據類型,也就是說不可以在原位置對其進行修改。
         如下圖:

 

只可以通過下標訪問,不能通過下標修改其值:

>>> s = 'ixusy88'
>>> s[0]
'i'
>>> s[0]=1
Traceback (most recent call last):
  File "<pyshell#33>", line 1, in <module>
    s[0]=1
TypeError: 'str' object does not support item assignment
>>> 

2:常見的字符串字面量和操作

常見的字符串字面量和操作()

操作

說明

s = ''

空字符串

s = "ixusy's"

雙引號,單引號

s = 'i\nx\ta\x30m'

轉義系列

s= """ more lines

    new line

"""

三引號塊字符串

s = r'D:\python\test'

原始字符串(不需要進行轉義)

s= b'ixusy'

字節串

u'\u0069usy88'

Unicode字符串

s1 + s2  

拼接

s*5

重複

s[i]

索引

s[i:j]

分片  (返回結果是新的對象)

len(s)

長度

"name is %s" % ('ixusy88',)

字符串格式化

"name is {0}".format('ixusy88')

字符串格式化

name = 'ixusy88'

s = f"name is {name}"

字符串格式化

s.find(‘xu’)

字符串方法

s.rstrip()

移除右側空白

s.strip()

移除左側,右側空白

s.replace(‘xu’,’aaa’)

替換

s.split(‘,’)

用分隔符分組

‘,’.join(strlist)

分隔符連接

s.isdigit()

內容測試

s.lower()      s.upper

大小寫轉換

s.endswith(‘aaa’)

尾部測試

s.encode(‘utf8’)

Unicode編碼

B.decode(‘utf8’)

Unicode解碼

for c in s:print(c)

迭代

‘aaa’ in s

成員關係

map(ord,s)

ord返回字符串中單個字符的ascii碼

re.match(‘xx(.*)dd’,s)

模式匹配

更多方法執行下面語句查看:

print([item for item in dir(str) if not item.startswith('__') ])  查看,然後使用help函數查看對應函數,如下:

>>> print([item for item in dir(str) if not item.startswith('__') ])
['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> help(str.count)
Help on method_descriptor:

count(...)
    S.count(sub[, start[, end]]) -> int
    
    Return the number of non-overlapping occurrences of substring sub in
    string S[start:end].  Optional arguments start and end are
    interpreted as in slice notation.

>>> 

 

3:字符串的索引和切片
3.1:索引
索引就是下標. 切記, 下標從0開始,到字符串長度減1:

>>> s = 'hello'
>>> len(s)
5
>>> s[0]
'h'
>>> s[1]
'e'
>>> s[2]
'l'
>>> s[3]
'l'
>>> s[4]
'o'
>>> s[5]
Traceback (most recent call last):
  File "<pyshell#62>", line 1, in <module>
    s[5]
IndexError: string index out of range
>>> 

下標也可以是負數:
-1表示倒數第一個
-2表示倒數第二個

>>> s='hello'
>>> s[-1]
'o'
>>> s[-2]
'l'
>>> s[-3]
'l'
>>> s[-4]
'e'
>>> s[-5]
'h'
>>> s[-6]
Traceback (most recent call last):
  File "<pyshell#99>", line 1, in <module>
    s[-6]
IndexError: string index out of range
>>> 

 


3.2切片
我們可以使用下標來截取部分字符串的內容
  語法: str[start: end:step]      start默認爲0,end默認爲字符長度,step默認爲1
    start: 起始位置
  end: 結束位置
  step:步長
 規則: 顧頭不顧尾, 從start開始截取. 截取到end位置. 但不包括end (start<= x < end)
 step爲步長: 如果是正數, 則從左往右取. 如果是負數. 則從右往左取. 默認是1; 

>>> s = '中華人民共和國'
>>> print(len(s))
7
>>> 

# 不帶參數
#截取 下標0開始,右邊的所有字符,相當於複製了整個字符串
# 默認 0開始
#print(s[:])
>>> print(s[:])
中華人民共和國
>>> 
#截取 下標-1開始,左邊的所有字符,相當於複製了反轉之後的字符串
#默認 -1開始
>>> print(s[::-1])
國和共民人華中
>>> 



# 截取 下標爲2開始右邊的所有字符,結束位置默認爲字符串的長度
>>> print(s,s[2:])
中華人民共和國 人民共和國
>>> 
# 截取 下標爲2開始左邊的所有字符,
>>> print(s,s[2::-1])
中華人民共和國 人華中
>>> 

# 截取 下標爲2開始右邊的,直到下標5結束的所有字符(不包下標5的字符)
>>> print(s,s[2:5])
中華人民共和國 人民共
>>> 
# 截取 下標爲2開始左邊的,直到下標5結束的所有字符;結果爲空,因爲下標2左邊的下標均小於2,故不可能到達下標5
>>> print(s,s[2:5:-1])
中華人民共和國 
>>> 

 
# 截取 下標0開始,右邊,直到下標爲5結束的所有字符(不包下標5的字符); 
>>> print(s,s[:5])
中華人民共和國 中華人民共
>>> 
# 截取 下標-1開始,左邊,直到下標爲5結束的所有字符(不包下標5的字符);開始位置默認爲-1
>>> print(s,s[:5:-1])
中華人民共和國 國
>>> 


 

4:修改字符串

字符串是不可變數據類型,是不能在原位置修改的。這裏的修改是指通過拼接,替換等操作生成新的字符串;

# 拼接
s = 'ixusy88'
#print(s,s[:-2],s[-2:])
#如要在88前面增加字符串 'abc'
s =  s[:-2] + "abc" + s[-2:]
print(s)  # ixusyabc88

# 替換
# 要把88 替換爲abc
s = 'ixusy88'
s = s.replace('88','abc')
print(s)  # ixusyabc

# 通過轉換爲列表來修改,修改之後在連接爲字符串
# 要求把第三個字符u替換爲abc
s = 'ixusy88'
l = list(s)
# print(l)
l[2] = 'abc'
s=''.join(l)
print(s)  # ixabcsy88

5:字符串反斜槓字符

 

轉義

解釋

\\

反斜槓(保留一個\)

\’

單引號(保留’)

\”

雙引號(保留”)

\b

退格

\f

換頁

\n

換行

\r

回車

\t

水平製表符

\v

垂直製表

\xhh

十六進制值hh的字符

\ooo

八進制值ooo的字符

\0

空字符:二進制0字符

\uhhhh

16位十六進制值的Unicode字符

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章