時間:2022-12-06來源:www.djmaza-info.com作者:電腦系統城
作用:去除兩邊空格、左邊空格、右邊空格
1 2 3 4 |
s = " abcd " print ( "|" + s.strip() + "|" ) print ( "|" + s.lstrip() + "|" ) print ( "|" + s.rstrip() + "|" ) |
查看運行結果:
作用:移除前綴、移除后綴
1 2 3 |
s = "hello:world" print (s.removeprefix( "hello" )) print (s.removesuffix( "world" )) |
查看運行結果:
作用:替換字符串中的內容替換成指定的內容
1 2 3 |
s = "hello:world" s = s.replace( ":" , "-" ) print (s) |
查看運行結果:
作用:從左邊起根據對用的內容分割字符串、從右邊起根據對用的內容分割字符串(當指定字符串的分隔次數時存在區別)
1 2 3 4 5 |
s = "hello:world:ok" print (s.split( ":" )) print (s.rsplit( ":" )) print (s.split( ":" , maxsplit = 1 )) print (s.rsplit( ":" , maxsplit = 1 )) |
查看運行結果:
作用:將括號內的元素(均需要滿足字符串格式)合并成一個新的字符串,已join前的字符作為分隔符
1 2 3 |
l = [ "hello" , "1" , "world" ] print ("".join(l)) print ( "-" .join(l)) |
查看運行結果:
作用:將所有字母轉為大寫、將所有字母轉為小寫、將首字母轉為大寫
1 2 3 4 |
s = "helloWORLD" print (s.upper()) print (s.lower()) print (s.capitalize()) |
查看運行結果:
作用:檢查字符串中字母是否都為小寫、檢查字符串中字母是否都為大寫、檢查字符串中字符是否都是字母、檢查字符串中字符是否都是數字、檢查所有的字符串是否都是數字或字母
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
s1 = "helloworld" s2 = "OK" s3 = "hello OK" s4 = "567" s5 = "hello123" print (s1.islower()) print (s2.isupper()) print (s3.islower(), s3.isupper()) print (s1.isalpha()) print (s4.isnumeric()) print (s5.isalpha(), s5.isnumeric()) print (s5.isalnum()) print (s3.isalnum()) |
查看運行結果:
作用:返回指定內容在字符串中出現的次數
1 2 |
s = "hello world" print (s.count( "o" )) |
查看運行結果:
作用:返回字符串中是否包含指定內容的索引信息(從左邊開始第一個出現的),不包含時返回-1、返回字符串中是否包含指定內容的索引信息(從右邊開始第一個出現的),不包含時返回-1
1 2 3 4 |
s = "hello world" print (s.find( "x" )) print (s.find( "o" )) print (s.rfind( "o" )) |
查看運行結果:
作用:檢查字符串是否是以指定內容開頭、檢查字符串是否是以指定內容結束
1 2 3 |
s = "hello world" print (s.startswith( "h" ), s.endswith( "h" )) print (s.startswith( "d" ), s.endswith( "d" )) |
查看運行結果:
作用:有點像find()和split()的結合體。將字符串根據指定的內容拆分為三個元素的元祖,其中第二個元素為指定的內容,如果不包含指定的內容的話,返回的第一個元素為原字符串
1 2 3 4 |
s = "hello world" print (s.partition( " " )) print (s.partition( "hello" )) print (s.partition( "123" )) |
查看運行
作用:
返回一個原字符串居中,并使用指定內容(默認為空格)填充至長度width的新字符串
返回一個原字符串左對齊,并使用指定內容(默認為空格)填充至長度width的新字符串
返回一個原字符串右對齊,并使用指定內容(默認為空格)填充至長度width的新字符串。
1 2 3 4 5 |
s = "python" print (s.center( 30 )) print (s.center( 30 , "-" )) print (s.ljust( 30 , "-" )) print (s.rjust( 30 , "-" )) |
查看運行結果:
作用:是格式化字符串的新語法,更易讀,更簡潔,不易出錯,而且速度更快!需要python3.6+的版本支持
1 2 3 |
name = "bk" age = 15 print (f "my name is {name},and i am {age} years old!" ) |
查看運行結果:
作用:翻轉字符串中的字母大小寫
1 2 |
name = "My Name is Mr.white" print (name.swapcase()) |
查看運行結果:
作用:返回長度為width的字符串,原字符串string右對齊,前面填充0
1 2 3 4 |
print ( "100" .zfill( 5 )) print ( "+100" .zfill( 5 )) print ( "-100" .zfill( 5 )) print ( "+0010" .zfill( 5 )) |
查看運行結果:
到此這篇關于Python中字符串的常用方法總結的文章就介紹到這了,
2022-12-06
Python創建相同值數組/列表的兩種方法2022-12-06
Python實現短信驗證碼的發送2022-12-06
Python利用openpyxl類實現在Excel中繪制樂高圖案一.Pygame程序基本搭建過程 1.初始化化程序 2.創建Surface對象 3.事件監聽 4.游戲循環 二.Pygame Display顯示模塊詳解 1.將Surface對象粘貼至主窗口上 2.設置窗口主窗口 3.填充主窗口背景,參數值RGB 4.設置窗口標題 ...
2022-12-06
最近有許多小伙伴修改電腦的虛擬內存的時候不清楚8G的運行內存該設置多大的初始值和最大值,其實都是有公式的,現在就給大家具體介紹一下設置的方法。...
2022-10-22