python中的字符串切割 maxsplit
python 字符串切割 maxsplit
my_str.split(str1, maxsplit)
str1 可以不寫,默認是空白字符(" " “\t” “\n”)
將my_str 這個字符串按照str1 進行切割, maxsplit 割幾次
my_str = "hello world itcast and itcastcpp"
my_str1 = my_str.split(" ")
print(my_str1)
my_str2 = my_str.split(" ", 1)
print(my_str2)
my_str3 = my_str.split() # 用的最多
print(my_str3)
my_str4 = my_str.split("itcast")
print(my_str4)
# 輸出結(jié)果是
['hello', 'world', 'itcast', 'and', 'itcastcpp']
['hello', 'world itcast and itcastcpp']
['hello', 'world', 'itcast', 'and', 'itcastcpp']
['hello world ', ' and ', 'cpp']
python字符串切割split和rsplit函數(shù)
1. split(sep, maxsplit)
切分字符串,返回切分后的列表
sep,分隔符,默認空格
maxsplit,切分次數(shù),默認最大次數(shù),從起始位置開始計數(shù)
示例1:默認
s = 'a b c' res = s.split() res
['a', 'b', 'c']
示例2:指定參數(shù)
s = 'a b c' res = s.split(sep=' ', maxsplit=1) res
['a', 'b c']
示例3:位置參數(shù)
s = 'a.b.c'
res = s.split('.', 1)
res['a', 'b.c']
2. rsplit(sep, maxsplit)
類似split,區(qū)別為從結(jié)尾位置開始計數(shù)
sep,分隔符,默認空格
maxsplit,切分次數(shù),默認最大次數(shù),從起始結(jié)尾開始計數(shù)
示例1:默認
s = 'a b c' res = s.rsplit() res
['a', 'b', 'c']
示例2:指定參數(shù)
s = 'a b c' res = s.rsplit(sep=' ', maxsplit=1) res
['a b', 'c']
示例3:位置參數(shù)
s = 'a.b.c'
res = s.rsplit('.', 1)
res['a.b', 'c']
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
如何給pip更換國內(nèi)源并配置Python的國內(nèi)鏡像詳解
pip安裝的包都存在于外國的服務(wù)器上,速度會非常慢,可以給pip配置國內(nèi)鏡像,直接從國內(nèi)服務(wù)器安裝依賴,這篇文章主要介紹了如何給pip更換國內(nèi)源并配置Python的國內(nèi)鏡像的相關(guān)資料,需要的朋友可以參考下2025-04-04
Python3.6筆記之將程序運行結(jié)果輸出到文件的方法
下面小編就為大家分享一篇Python3.6筆記之將程序運行結(jié)果輸出到文件的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04
Python中使用partial改變方法默認參數(shù)實例
這篇文章主要介紹了Python中使用partial改變方法默認參數(shù)實例,本文直接給出使用實例,代碼中包含詳細注釋,需要的朋友可以參考下2015-04-04
翻轉(zhuǎn)數(shù)列python實現(xiàn),求前n項和,并能輸出整個數(shù)列的案例
這篇文章主要介紹了翻轉(zhuǎn)數(shù)列python實現(xiàn),求前n項和,并能輸出整個數(shù)列的案例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05

