網站首頁 編程語言 正文
字符串
字符串常用操作
拼接字符串
拼接字符串需要使用‘+’運算符可完成對多個字符串的拼接。如
str = "a"+"b"
字符串不允許直接與其他類型的數據拼接,需要將其他類型轉換為字符串才可以進行拼接。
字符串復制
使用運算符 * 重復輸出字符串
str = "hello world"*2
print(str)# hello worldhello world
計算字符串的長度
不同的字符所占字節數不同,在python中數字、英文、小數點、下劃線和空格占一個字節,一個漢字可能會占2~4個字節,取決于采用的編碼。漢字在GBK/GB2312編碼中占2個字節,在UTF-8/Unicode編碼中一般占用3個字節(或4個字節)。python中默認的編碼格式是UTF-8,即一個漢字占3個字節。python中,提供了內置函數len()計算字符串的長度,默認情況下通過len()函數計算字符串的長度時,不區分英文、數字和漢字,所有字符都按照一個字符來計算
str = "hello world"
len = len(str)
print(len)# 11
截取字符串和獲取單個字符
通過索引 [] 獲取字符串中指定位置的字符
str = "hello world"
print(str[0])# h
print(str[1])# e
在 Python 中,使用語法 string[start:end],獲取字符串 string 中在 [start, end) 范圍的子字符串。注意范圍 [start, end) 包含 start,不包含 end。舉例如下:
str = "hello world"
print(str[0:3])# hel
print(str[:5]) # hello
print(str[-3:]) # rld
print(str[3:])# lo world
print(str[:])# hello world
字符串包含判斷
通過關鍵字 in 檢查字符串中是否包含指定字符串
pd = "hello" in "hello world" # hello world 是否包含 hello
print(pd) # True
pd = "hello" not in "hello world" # hello world 是否不包含 hello
print(pd) # False
常用字符串方法
把字符串的第一個字符大寫
capitalize() 方法把字符串的第一個字符大寫,示例如下:
text = 'abc'
text = text.capitalize()
print(text) # Abc
統計字符串出現的次數
count() 方法用于檢索指定字符串中在另一個字符串中出現的次數,如果檢索的字符串不存在,則返回0,否則返回出現的次數。
text = 'abc abc'
count = text.count('abc') # 2
print(count)
檢查字符串開頭
startswith() 方法用于檢索字符串是否以指定的子字符串開頭,如果是則返回True,否則返回False。
text = 'abc'
pd = text.startswith('ab')
print(pd)
檢查字符串結尾
endswith() 方法用于檢索字符串是否以指定的子字符串結尾,如果是則返回True,否則返回False
text = 'abc'
pd = text.endswith('bc')
print(pd)
大寫轉小寫
lower() 方法用于將字符串中的大寫字母轉換為小寫字符,如果字符串中沒有需要轉換的字符,則將原字符串返回。
text = 'ABC'
lower = text.lower()
print(lower) # abc
小寫轉大寫
upper() 方法用于將字符串中的大寫字母轉換為小寫字符,如果字符串中沒有需要轉換的字符,則將原字符串返回。
str1 = "asdfg"
print(str1.upper())
大小寫翻轉
swapcase() 方法用于對字符串的大小寫字母進行轉換,即將大寫字母轉換為小寫字母,小寫字母會轉換為大寫字母。
str1 = 'avvvv'
print(str1.swapcase())
標題化字符串
istitle() 方法檢測字符串中所有的單詞拼寫首字母是否為大寫,且其他字母為小寫。如果字符串中所有的單詞拼寫首字母是否為大寫,且其他字母為小寫則返回 True,否則返回 False.
str = "This is string example....wow!!!";
print str.istitle();
title() 方法返回"標題化"的字符串,就是說所有單詞都是以大寫開始,其余字母均為小寫
str = "this is string example....wow!!!"
print(str.title())# This Is String Example....Wow!!!
空格刪除
text = ' abcdaaa '
print(text.strip()) # 刪除開始和結尾的空格
print(text.lstrip()) # 刪除左邊的空格
print(text.rstrip()) # 刪除右邊的空格
合并字符串
合并字符串與拼接字符串不同,它可以將多個字符串采用固定的分隔符連接在一起。合并字符串可以使用字符串對象的join() 方法實現
text = 'abc'
print(text.join("def"))
分割字符串
分割字符串是把字符串分割為列表,通過split() 函數可以實現字符串分割,也就是把一個字符串按照指定的分隔符切分為列表。
text = 'hello,a,v,c'
print(text.split(',')) # ['hello', 'a', 'v', 'c']
將字符串按照行分割
splitlines() 按照行(‘\r’, ‘\r\n’, \n’)分隔,返回一個包含各行作為元素的列表,如果參數 keepends 為 False,不包含換行符,如果為 True,則保留換行符。
str1 = 'ab c\n1111\nde fg\rkl\r\n'
print(str1.splitlines()) # ['ab c', '1111', 'de fg', 'kl']
判斷字符串只是數字
isnumeric() 方法檢測字符串是否只由數字組成。如果字符串中只包含數字字符,則返回 True,否則返回 False
str = "2009"
print( str.isnumeric()) # True
判斷是空字符
isspace() 方法檢測字符串是否只由空格組成。 如果字符串中只包含空格,則返回 True,否則返回 False.
str = " ";
print str.isspace();
字符串填充
zfill() 方法返回指定長度的字符串,不夠的長度的原字符串前面填充0。
str = "this is string example....wow!!!"
print(str.zfill(40)) # 00000000this is string example....wow!!!
ljust() 方法和zfill一樣,默認填充空白,我們可以指定填充的內容,填充的方向是右側
str = "this is string example....wow!!!"
print(str.ljust(40,'0')) # this is string example....wow!!!00000000
字符串搜索
find() 方法用于檢索是否包含指定的子字符串,如果檢索的字符串不存在責返回-1,否則返回首次出現該子字符串時的索引
text = 'abcdef'
print(text.find("cd")) # 2
python還提供了rfind() 方法,其作用和find() 方法類似,只是從字符串右邊開始檢索。
python還提供了index() 方法同find() 方法類似,也是用于檢索是否包含指定的子字符串。只不過是用index() 方法時,當指定的字符串不存在時則會拋出異常
python還提供了rindex() 方法其作用同index() 方法類似,只是從字符串右邊開始檢索。
字符串替換
replace() 方法把字符串中的 old(舊字符串) 替換成 new(新字符串),如果指定第三個參數max,則替換不超過 max 次。
參數
old – 將被替換的子字符串。
new – 新字符串,用于替換old子字符串。
max – 可選字符串, 替換不超過 max 次 (默認最大)
str = "this is string example....wow!!! this is really string"
print(str.replace("is", "was"))
格式化字符串
格式化字符串是指先制定一個模板,在這個模板中預留幾個空位,然后在根據需要填上相對應的內容。這些空位需要通過指定的符號標記(也稱為占位符),而這些符號還不會顯示出來。
python中提供了如下兩種方法格式化字符串:
使用’%’ 操作符
text = 'hello %s' % 'java'
print(text) # hello java
text = 'hello %s %s' % ('java', 'python')
print(text) # hello python world
使用字符串對象的format() 方法
在創建模板時需要使用’{}‘和’:’ ,指定占位符,例如:
字符串編碼轉換
Python 3.x 默認采用 UTF-8 編碼格式,有效地解決了中文亂碼的問題。但是有些時候數據是第三方獲取的,那么我們就不能保證編碼就是UTF-8的所以我們就需要進行編碼轉換了
編碼
encode() 方法用于將 str 類型轉換成 bytes 類型,這個過程也稱為“編碼”。str.encode([encoding="utf-8"][,errors="strict"])
注意:格式中用 [] 括起來的參數為可選參數,也就是說,在使用此方法時,可以使用 [] 中的參數,也可以不使用。該方法各個參數的含義如表 所示。
注意:使用 encode() 方法對原字符串進行編碼,不會直接修改原字符串,如果想修改原字符串,需要重新賦值。
str = "中文網"
encode = str.encode('utf-8') # 返回的類型為bytes
print(encode) # b'\xe4\xb8\xad\xe6\x96\x87\xe7\xbd\x91'
解碼
和 encode() 方法正好相反,decode() 方法用于將 bytes 類型的二進制數據轉換為 str 類型,這個過程也稱為“解碼”。bytes.decode([encoding="utf-8"][,errors="strict"])該方法中各參數的含義如表所示。
str = "中文網"
encode = str.encode('utf-8')
decode = encode.decode('utf-8')
print(decode) # 中文網
原文鏈接:https://blog.csdn.net/weixin_45203607/article/details/126573874
相關推薦
- 2022-05-25 Redis的安裝和使用(windows)
- 2022-06-19 python繪制橫豎條形圖的方法_python
- 2022-11-20 C#設計模式之裝飾器模式實例詳解_C#教程
- 2022-08-13 Spring Boot 攔截器
- 2022-09-22 k8s 存儲卷之 PV & PVC
- 2022-08-05 EasyExcel 3.X 簡單寫入Excel文件數據
- 2022-03-08 android?studio組件通信:Intend啟動Activity接收返回結果_Android
- 2022-05-20 springboot心跳機制,定時任務
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支