超詳細!盤點Python中字符串的經常使用操做

在Python中字符串的表達方式有四種python

  • 一對單引號
  • 一對雙引號
  • 一對三個單引號
  • 一對三個雙引號
a = 'abc'
b= "abc"
c = '''abc'''
d = """abc"""
print(type(a)) # <class 'str'>
print(type(b)) # <class 'str'>
print(type(c)) # <class 'str'>
print(type(d)) # <class 'str'>

單雙引號混合使用

a = "LiMing say 'nice to meet you'"

一樣也能夠經過轉義的方式不用在裏面寫雙引號git

a = "LiMing say \"nice to meet you\""
print(a)

總結就是須要外面用了雙引號,裏面須要引用的語句能夠用單引號括起來,反之亦然。api

一般狀況根據我的喜愛,基本都是使用單引號或者雙引號。有些特殊狀況,好比須要表示多行時,能夠選擇三個單(雙)引號,而且無序用\進行轉移,可直接使用單引號和雙引號。函數

a = '''
    My Name is 阿亮,
    Let's say 'Hello'
    '''
print(a)

字符串的下標和切換

下標:字符串是一個個字符拼接而成,下標能夠理解爲每一個字符的編號,從0開始依次類推。code

做用:經過下標去操做字符串中的元素orm

# H的下標爲0, e的下標爲1 ..依次類推
a = 'HelloWorld'

# 獲取字符串a中下標爲4的元素
print(a[4])  # o  下標爲4的元素爲o

修改字符串中的元素是否是能夠直接賦值呢? 例如:blog

a = 'HelloWorld'

a[4] = 'k'
print(a)

上面的代碼運行以後發現報錯。索引

TypeError: 'str' object does not support item assignment

緣由是由於: 字符串一旦建立以後,裏面的元素是不能夠修改的。ip

因此字符串是沒法直接進行修改的。字符串

字符串運算

字符串運算中用到了+*><!== 等邏輯運算符。

字符串的相加操做,也能夠理解爲拼接操做。例如:

a = 'Hello' + ' World'
print(a) # Hello World

# 也能夠寫成
a = 'Hello' ' World'
print(a) # Hello World

字符串的乘法操做, 能夠理解爲克隆操做,字符串只能與整數(n)想乘,表明克隆n個字符串。

a = 'a'
print(a * 2) # aa
b = '-'
print(b * 10) # ----------

切片

字符串的切片也稱爲字符串截取。 全部操做都是經過字符串的下標進行操做的。

用法:字符串[開始索引(start):結束索引(end):步長(step)(默認1)]

步長(step):每隔(step-1)個取一個元素,當step爲負數時,表明從右向左取元素,

a = 'abcdefghijklmn'

# 從下標1開始 到4結束 進行切片  (包括1,不包括4,即左開又閉)
print(a[1:4]) # bcd
print(a[1:8]) # bcdefgh
print(a[1:8:2])# 步長爲2, 結果:bdfh

# 當補償爲負數時,表明逆向截取。 初始從座標8開始,每隔一個元素取一個值,到下標爲1時結束
print(a[8:1:-2]) # igec

字符串的經常使用操做

這裏以代碼+註釋的方式,展現幾個經常使用的字符串操做。

a = ' Hello World '

# 獲取字符串的長度
print(len(a)) # 13

# 刪除字符串兩邊的空格
print(a.strip()) # Hello World

# 刪除左邊的空格
print(a.lstrip()) # Hello World (只刪除左邊的空格)

# 刪除字符串右邊的空格
print(a.rstrip()) #  Hello World

# 經過指定鏈接符 連接字符串
lst = ['LiMing', 'Tom']
print('***'.join(lst)) # LiMing***Tom

# 首字母大寫
m = 'hello world'
print(m.capitalize()) # Hello world
# 返回標題化字符串,即每一個單詞首字母大寫
print(m.title()) # Hello World

# 打印輸出字符,將字符串放在中間,
# center(width, fillchar)   width: 字符串的總長度, fillchar:填充字符
print(a.center(20, '*')) # *** Hello World ****

# 是否以xxx開頭
n = 'Hello'
print(n.startswith('H')) # True

# 是否以xxx結尾
print(n.endswith('o')) # True

# 字符串是全純英文字符
print(a.isalpha()) # False , 由於字符串a中 ' Hello World ' 有空格,所以返回False
print('HelloWorld'.isalpha()) #True

# 判斷字符串中是否所有爲數字或者英文
print('Hello2World'.isalnum()) # True
print('123'.isalnum()) # True
print('abc&11'.isalnum()) # False

# 判斷是否爲整數
print('123'.isdigit()) # True
print('1.23'.isdigit()) # False

# 判斷字符是否全爲小寫
print('abc'.islower()) # True

# 判斷字符是否全爲大寫
print('Abc'.isupper()) # False
print('ABC'.isupper()) # True

# 字符串小寫轉大寫
print('abc'.upper()) # ABC

# 字符串大寫轉小寫
print('ABC'.lower()) # abc

# 字符串的替換
b = 'aabbcc'.replace('a', 'm')
print(b) # mmbbcc
#  1 表明替換的個數
b = 'aabbcc'.replace('a', 'm', 1)
print(b) # mabbcc

# split 字符串切割,默認空格切割
print('aa bb cc'.split()) # ['aa', 'bb', 'cc']
print('ab,cd,ef'.split(',')) # ['ab', 'cd', 'ef']

# 字符串換行分割
a = """
    My Name is 'Python極客專欄',
    歡迎關注
    """
print(a.splitlines()) # ['', "    My Name is 'Python極客專欄',", '    歡迎關注', '    ']

字符串的查找

字符串查找經常使用的方法用indexfind

二者功能類似,區別在於find查找不到元素時返回 -1, 不會影響程序運行,而index則會拋出異常。

a = 'abcdef'
# 查找到元素返回對應的下標
print(a.find('c')) # 2
print(a.find('h')) # -1

print(a.index('c')) # 2
print(a.index('h')) # 拋出異常,ValueError: substring not found
rfind: 相似於find()函數,不過是從右邊開始查找;返回字符串最後一次出現的位置,若是沒有匹配項則返回-1 。rindex 同理
a = 'acmncd'
# 從右邊開始計算,返回第一個匹配到的下標
print(a.rfind('c')) # 4
print(a.rindex('c')) # 4

字符串的格式化

name = 'Python極客專欄'
# %s 用於輸出字符串
print('個人公衆號是: %s' % name)
age = 18
# %d 用於輸出十進制數字
print('個人年齡是:%d' % age)
money = 1.23
# %f 浮點數,默認顯示小數點後6位
print('我身上有:%f 元' % money )
# 指定小數點後的位數
print('我身上有:%.2f 元' % money )
format操做

除了使用 % 進行格式化,也可使用format

print('{} {}'.format('Hello', 'World')) # Hello World
print('{0} {1}'.format('Hello', 'World')) # Hello World

print('公衆號{name}, 分享{code} 技術'.format(name='Python極客專欄', code='Python')) # 公衆號Python極客專欄, 分享Python 技術

print('{1}, {0}, {1}'.format('A', 'B')) #B, A, B

print('今年是 {}年.'.format(2020)) # 今年是 2020年.

文末福利,史上最全Python資料彙總(長期更新)。隔壁小孩都饞哭了 --- 點擊領取

相關文章
相關標籤/搜索