Python中常用的8種字符串操作方法

Python中常用的8種字符串操作方法

一、拼接字符串

使用“+”可以對多個字符串進行拼接

語法格式: str1 + str2

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

需要注意的是字符串不允許直接與其他類型進行拼接,例如

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

上面這種情況我們可以將num轉換為字符串再進行拼接

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

這樣就不會報錯了

二、計算字符串的長度

在Python中使用len()函數來計算字符串的長度

語法格式: len(string)

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

從上面的結果我們可以看出,在默認情況下,len函數在計算字符串的長度時,無論是數字,字母還是多字節的漢字都認為是一個字符。

為什麼說是默認情況下呢,因為在實際開發中,可能因為我們採取的編碼不同,字符串實際所佔的字節數也不同。

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

這時我們可以通過使用encode()方法進行編碼後再進行獲取長度。

例如:

<code>>>> str1 = "你好"
>>> len(str1)
2
>>> len(str1.encode('gbk'))
4

>>> len(str1.encode('utf-8'))
6/<code>

三、截取字符串

語法格式: string[start : end : step]

參數說明

  • string:表示要截取的字符串
  • start:表示要截取的第一個字符的索引(包括該字符),如果不指定,則默認為0
  • end:表示要截取的最後一個字符的索引(不包括該字符),如果不指定則默認為字符串的長度。
  • step:表示切片的步長,如果省略,則默認為1,當省略該步長時,最後一個冒號也可以省略。
<code>>>> 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'/<code>

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

四、分割字符串

python中分割字符串是使用split()方法把字符串分割成列表

語法格式 : str.split(sep, maxsplit)

參數說明:

  • str:表示要進行分割的字符串
  • sep:用於指定分隔符,可以包含多個字符,默認為None,即所有空字符(包括空格、換行"n”、製表符“t”等)。
  • maxsplit:可選參數,用於指定分割的次數,如果不指定或者為-1,則分割次數沒有限制,否則返回結果列表的元素個數最多為 maxsplit+1
  • 返回值:分隔後的字符串列表。
<code>>>> 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!']/<code>

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

五、檢索字符串

python中字符串的查找方法

1、count()方法

語法格式 : str.count(sub[, start[, end]])

作用:用於檢索指定字符串在另一個字符串中出現的次數,如果檢索的字符串不存在則返回0,否則返回出現的次數。

參數說明

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

2、find()方法

語法格式 : str.find(sub[, start[, end]])

作用:檢索是否包含指定的字符串,如果檢索的字符串不存在則返回-1,否則返回首次出現該字符串時的索引。

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

3、index()方法

語法格式 : str.index(sub[, start[, end]])

作用:和find方法類似,也用於檢索是否包含指定的字符串,使用index方法,當指定的字符串不存在時會拋異常。

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

4、startswith()方法

語法格式 : str.startswith(prefix[, start[, end]])

作用:檢索字符串是否以指定的字符串開頭,如果是則返回true,否則返回false。

<code>>>> str1 = "hello world!"
>>> str1.startswith('hello')

True
>>> str1.startswith('hi')
False
>>>/<code>

5、endswith()方法

語法格式 : str.endswith(prefix[, start[, end]])

作用:檢索字符串是否以指定的字符串結尾,如果是則返回true,否則返回false。

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

6·字符串的大小寫轉換

1、lower()方法

語法格式 : str.lower()

作用:將字符串中的大寫字母轉換為小寫字母

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

2、upper()方法

語法格式 : str.upper()

作用:將字符串中的小寫字母轉換為大寫字母

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

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

開發中,我們會遇到這樣的需求,字符串前後(左右側)不允許出現空格和特殊字符或者將用戶輸入的字符串中誤輸入的空格去除掉。這時我們就需要用到strip函數。

1、strip()方法

語法格式 : str.strip([chars])

作用:去除字符串前後(左右側)的空格或特殊字符

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

2、lstrip()方法

語法格式 : str.lstrip([chars])

作用:去除字符串前面(左側)的空格或特殊字符

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

3、rstrip()方法

語法格式 : str.rstrip([chars])

作用:去除字符串後面(右側)的空格或特殊字符

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

七、格式化字符串

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

八、使用“%”操作符

語法格式: '%[-][+][0][.n]格式化字符'%exp

參數說明

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


Python中常用的8種字符串操作方法

exp:要轉換的項,如果要指定的項有多個,需要通過元組的形式進行指定,但不能使用列表。

<code>>>> template = '學號:%d,姓名:%s,班級:%s'
>>> print(template% (123,'張三','一年級'))
學號:123,姓名:張三,班級:一年級/<code>

最後,小編想說:我是一名python開發工程師,

整理了一套最新的python系統學習教程,

想要這些資料的可以關注私信小編“01”即可(免費分享哦)希望能對你有所幫助


分享到:


相關文章: