python字符串操作詳析
字符串是不可變類型,可以重新賦值,但不可以索引改變其中一個值,只能拼接字符串建立新變量
索引和切片
索引:越界會報錯切片:
越界會自動修改
不包含右端索引
需重小到大的寫,否則返回空字符串
motto = '積善有家,必有余慶。' # 索引 print(motto[0]) # print(motto[10]) 報錯 # 切片 ?不包含右側 ?從小到大 print(motto[0:9]) print(motto[0:10]) print(motto[0:100]) print(motto[0:]) print(motto[-10:]) print(motto[-100:]) print(motto[-5:-1]) print(motto[0:10:2]) print(motto[:5]) print(motto[3:2]) ?# 若大到小,則返回'' print(motto[2:3])
一、5種字符串檢索方法
s = "ILovePython" # 1. str.count('',起點,終點) print(s.count('o', 1, 5)) print(s.count('o')) # 2. str.find('',起點,終點) ?找不到返回-1 print(s.find('o',3)) print(s.find('o',3,5)) print(s.find('o')) # 3. str.index('',起點,終點) ? 找不到則報錯 print(s.index('o')) print(s.index('Py')) # 4. str.startswith('',起點,終點) print(s.startswith("IL")) print(s.startswith("L")) # 5. str.endswith('',起點,終點) print(s.endswith("on")) print(s.endswith("n")) print(s.endswith("e"))
1 2 9 -1 2 2 5 True False True True False
二、join字符串拼接方法 [列表/元組 --> 字符串]
將列表元組,拼接成字符串
# join()函數 ? list_val = ['www', 'baidu', 'com'] str_val = '.'.join(list_val) print(str_val) tuple = ('Users', 'andy', 'code') str_val = '/'.join(tuple) print(str_val)
三、3種字符串分割方法 [字符串 --> 列表/元組]
# 1. split('',分割次數) ? 默認從空格 \n \r \t切掉 s = "我 愛\t你\nPy thon" print(s.split()) s1 = "python我愛你Python" print(s1.split("y")) s2 = "python我愛你Python" print(s1.split("y", 1)) # 2. splitlines() ?默認從換行符rt切掉 s = "我 愛\t你\nPy thon" print(s.splitlines()) # 3. partition('') ?不切掉 分成3元素元組 s = "我愛你Python" print(s.partition('愛'))
['我', '愛', '你', 'Py', 'thon'] ['p', 'thon我愛你P', 'thon'] ['p', 'thon我愛你Python'] ['我 愛\t你', 'Py thon'] ('我', '愛', '你Python')
split()和splitlines()默認情況下的對比:
split()
和partition()
對比:split()切掉后變列表,partition()不切掉變元組
四、5種大小寫轉換方法
string_val = 'I love Python' print(string_val.upper()) print(string_val.lower()) print(string_val.title()) ?# 每個單詞第一個字母變大寫 print(string_val.capitalize()) ?# 僅第一個字母變大寫 print(string_val.swapcase())
I LOVE PYTHON i love python I Love Python I love python i LOVE pYTHON
五、3種字符串修剪方法
默認首尾的空格和換行符\t\r進行修剪
可用參數設定首尾的其他符號進行修剪
lstrip()
只刪首rstrip()
只刪尾
s = " ? ? ILovepython" print(s) print(s.strip()) print(s.strip(' ? ? I')) print(s.strip('n')) s1 = "00000003210Runoob0123000000" print(s1.strip('0')) print(s1.lstrip('0')) print(s1.rstrip('0'))
?ILovepython ILovepython Lovepython 3210Runoob0123 3210Runoob0123000000 00000003210Runoob0123
到此這篇關于python字符串操作的文章就介紹到這了,更多相關python字符串操作內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
pytorch中 gpu與gpu、gpu與cpu 在load時相互轉化操作
這篇文章主要介紹了pytorch模型載入之gpu和cpu互轉操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05