1. 程式人生 > 其它 >Python中常用的8種字串操作方法

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

一、拼接字串

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

語法格式: str1 + str2

>>> 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

  

二、計算字串的長度

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

語法格式: len(string)

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

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

為什麼說是預設情況下呢,因為在實際開發中,可能因為我們採取的編碼不同,字串實際所佔的位元組數也不同。

  • 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]

引數說明

  • 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開始的

四、分割字串

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中字串的查詢方法

1、count()方法

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

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

引數說明

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

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

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

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

3、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

4、startswith()方法

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

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

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

5、endswith()方法

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

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

 

六、字串的大小寫轉換

1、lower()方法

語法格式 :str.lower()

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

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

2、upper()方法

語法格式 :str.upper()

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

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

 

八、去除字串中的空格和特殊字元

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

1、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!'

 

2、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!@.'

 

3、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!'

  

格式化字串

Python2.6 開始,新增了一種格式化字串的函式str.format(),它增強了字串格式化的功能。

基本語法是通過{}和:來代替以前的%。

format 函式可以接受不限個引數,位置可以不按順序。

>>>"{} {}".format("hello", "world")    # 不設定指定位置,按預設順序
'hello world'
 
>>> "{0} {1}".format("hello", "world")  # 設定指定位置
'hello world'
 
>>> "{1} {0} {1}".format("hello", "world")  # 設定指定位置
'world hello world'

也可以設定引數:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
print("網站名:{name}, 地址 {url}".format(name="小風教程", url="www.runoob.com"))
 
# 通過字典設定引數
site = {"name": "小風教程", "url": "www.runoob.com"}
print("網站名:{name}, 地址 {url}".format(**site))
 
# 通過列表索引設定引數
my_list = ['小風教程', 'www.runoob.com']
print("網站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必須的

  輸出結果為:

網站名:小風教程, 地址 www.runoob.com
網站名:小風教程, 地址 www.runoob.com
網站名:小風教程, 地址 www.runoob.com

  也可以向str.format()傳入物件:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class AssignValue(object):
    def __init__(self, value):
        self.value = value
my_value = AssignValue(6)
print('value 為: {0.value}'.format(my_value))  # "0" 是可選的

  輸出結果為:

value 為: 6

  

奔跑的蝸牛