【思惟導圖】Python中經常使用的8種字符串操做

文章末尾獲取思惟導圖高清源文件
python

拼接字符串

使用「+」能夠對多個字符串進行拼接
語法格式str1 + str2shell

>>> str1 = "aaa"
>>> str2 = "bbb"
>>> print(str1 + str2)
aaabbb

須要注意的是字符串不容許直接與其餘類型進行拼接,例如函數

>>> num = 100
>>> str1 = "hello"
>>> print(str1 + num)
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    print(str1 + num)
TypeError: can only concatenate str (not "int") to str

上面這種狀況咱們能夠將num轉換爲字符串再進行拼接編碼

>>> num = 100
>>> str1 = "hello"
>>> print(str1 + str(num))
hello100

這樣就不會報錯了spa

計算字符串的長度

在Python中使用len()函數來計算字符串的長度
語法格式len(string)code

>>> str1 = "hello"
>>> len(str1)
5
>>> str2 = "你好"
>>> len(str2)
2
>>> str3 = "1111"
>>> len(str3)
4

從上面的結果咱們能夠看出,在默認狀況下,len函數在計算字符串的長度時,不管是數字,字母仍是多字節的漢字都認爲是一個字符。
爲何說是默認狀況下呢,由於在實際開發中,可能由於咱們採起的編碼不一樣,字符串實際所佔的字節數也不一樣。blog

  • UTF-8編碼,漢字佔3個字節
  • GBK或者GB2312,漢字佔2個字節

這時咱們能夠經過使用encode()方法進行編碼後再進行獲取長度。
例如:索引

>>> str1 = "你好"
>>> len(str1)
2
>>> len(str1.encode('gbk'))
4
>>> len(str1.encode('utf-8'))
6

截取字符串

語法格式string[start : end : step]
參數說明ip

  • string:表示要截取的字符串
  • start:表示要截取的第一個字符的索引(包括該字符),若是不指定,則默認爲0
  • end:表示要截取的最後一個字符的索引(不包括該字符),若是不指定則默認爲字符串的長度。
  • step:表示切片的步長,若是省略,則默認爲1,當省略該步長時,最後一個冒號也能夠省略。
>>> str1 = "hello world!"
>>> str1[1]     #截取第2個字符
'e'
>>> str1[2:]    #從第3個字符開始截取
'llo world!'
>>> str1[:4]
'hell'
>>> str1[1:5]
'ello'
>>> str1[-1]    #截取最後一個字符
'!'
>>> str1[2:-2]
'llo worl'

注意:字符串的索引是從0開始的utf-8

分割字符串

python中分割字符串是使用split()方法把字符串分割成列表
語法格式str.split(sep, maxsplit)
參數說明:

  • str:表示要進行分割的字符串
  • sep:用於指定分隔符,能夠包含多個字符,默認爲None,即全部空字符(包括空格、換行"n」、製表符「t」等)。
  • maxsplit:可選參數,用於指定分割的次數,若是不指定或者爲-1,則分割次數沒有限制,不然返回結果列表的元素個數最多爲 maxsplit+1
  • 返回值:分隔後的字符串列表。
>>> str1 = "i am a good boy!"
>>> str1.split()    #採用默認分割符進行分割
['i', 'am', 'a', 'good', 'boy!']
>>> str1.split(" ")   #採用空格進行分割
['i', 'am', 'a', 'good', 'boy!']
>>> str1.split(" ", 3)  #採用空格進行分割,而且只分割前3個
['i', 'am', 'a', 'good boy!']

注意默認狀況下按空格分割

檢索字符串

python中字符串的查找方法
一、count()方法
語法格式str.count(sub[, start[, end]])
做用:用於檢索指定字符串在另外一個字符串中出現的次數,若是檢索的字符串不存在則返回0,不然返回出現的次數。
參數說明

  • str:表示原字符串
  • sub:表示要檢索的子字符串
  • start:可選參數,表示檢索範圍的起始位置的索引,若是不指定,則從頭開始檢索
  • end:可選參數,表示檢索範圍的結束位置的索引,若是不指定,則一直檢索到結尾
>>> str1 = "hello world"
>>> print(str1.count('o'))
2

二、find()方法
語法格式str.find(sub[, start[, end]])
做用:檢索是否包含指定的字符串,若是檢索的字符串不存在則返回-1,不然返回首次出現該字符串時的索引。

>>> str1 = "hello world!"
>>> str1.find('wo')
6

三、index()方法
語法格式str.index(sub[, start[, end]])
做用:和find方法相似,也用於檢索是否包含指定的字符串,使用index方法,當指定的字符串不存在時會拋異常。

>>> str1 = "hello world!"
>>> str1.index('w')
6
>>> str1.index('m')
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    str1.index('m')
ValueError: substring not found
>>> str1.find('m')
-1

四、startswith()方法
語法格式str.startswith(prefix[, start[, end]])
做用:檢索字符串是否以指定的字符串開頭,若是是則返回true,不然返回false。

>>> str1 = "hello world!"
>>> str1.startswith('hello')
True
>>> str1.startswith('hi')
False
>>>

五、endswith()方法
語法格式str.endswith(prefix[, start[, end]])
做用:檢索字符串是否以指定的字符串結尾,若是是則返回true,不然返回false。

>>> str1 = "hello world!"
>>> str1.endswith('world!')
True
>>> str1.endswith('haha')
False

字符串的大小寫轉換

一、lower()方法
語法格式str.lower()
做用:將字符串中的大寫字母轉換爲小寫字母

>>> str1 = "Hello World!"
>>> str1.lower()
'hello world!'

二、upper()方法
語法格式str.upper()
做用:將字符串中的小寫字母轉換爲大寫字母

>>> str1 = "Hello World!"
>>> str1.upper()
'HELLO WORLD!'

去除字符串中的空格和特殊字符

開發中,咱們會遇到這樣的需求,字符串先後(左右側)不容許出現空格和特殊字符或者將用戶輸入的字符串中誤輸入的空格去除掉。這時咱們就須要用到strip函數。
一、strip()方法
語法格式str.strip([chars])
做用:去除字符串先後(左右側)的空格或特殊字符

>>> str1 = "   hello  world!   "
>>> str1.strip()
'hello  world!'
>>> str2 = "#hello world#@#"
>>> str2.strip('#')
'hello world#@'
>>> str3 = "@hello world!@."
>>> str3.strip('@.')
'hello world!'

二、lstrip()方法
語法格式str.lstrip([chars])
做用:去除字符串前面(左側)的空格或特殊字符

>>> str1 = "   hello  world!   "
>>> str1.lstrip()
'hello  world!   '
>>> str2 = "#hello world#@#"
>>> str2.lstrip('#')
'hello world#@#'
>>> str3 = "@.hello world!@."
>>> str3.lstrip('@.')
'hello world!@.'

三、rstrip()方法
語法格式str.rstrip([chars])
做用:去除字符串後面(右側)的空格或特殊字符

>>> str1 = "   hello  world!   "
>>> str1.rstrip()
'   hello  world!'
>>> str2 = "#hello world#@#"
>>> str2.rstrip('#')
'#hello world#@'
>>> str3 = "@.hello world!@."
>>> str3.rstrip('@.')
'@.hello world!'

格式化字符串

所謂格式化字符串就是先制定一個模板,在模板中預留幾個空位,而後根據須要填上相應的內容。

使用「%」操做符

語法格式'%[-][+][0][.n]格式化字符'%exp
參數說明

  • -:可選參數,用於指定左對齊,正數前方無符號,負數前面加負號
  • +:可選參數,用於指定右對齊,正數前方加正號,負數前方加負號
  • 0:可選參數,表示右對齊,正數前方無符號,負數前方加負號,用0填充空白處(通常與m參數一塊兒使用)
  • m:可選參數,表示佔有寬度
  • n:可選參數,表示小數點後保留的位數
  • 格式化字符:用於指定類型,其值以下表所示

  • exp:要轉換的項,若是要指定的項有多個,須要經過元組的形式進行指定,但不能使用列表。
>>> template = '學號:%d,姓名:%s,班級:%s'
>>> print(template% (123,'張三','一年級'))
學號:123,姓名:張三,班級:一年級

好了,關於Python中字符串的操做方法就介紹到這裏,但願能夠幫助到你們。
須要思惟導圖源文件的請留言你的郵箱

相關文章
相關標籤/搜索