日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python中split()函數的用法詳解_python

作者:請叫我初學者 ? 更新時間: 2023-03-16 編程語言

一、split()函數的簡單應用

1.join()函數

Python join() 方法用于將序列中的元素以指定的字符連接生成一個新的字符串。
join()函數是 split() 方法的逆方法,用來將列表(或元組)中包含的多個字符串連接成一個字符串。

newstr=str.join(sequence)

newstr – 表示合并后生成的新字符串
sequence – 要連接的元素序列,必須為可迭代對象。
返回通過指定字符連接序列中元素后生成的新字符串。

舉例如下:
將元組中的字符串合并成一個字符串:

寫法1:
>>> symbol="-"    # 連接符
>>> seq=("I","love","China")   # 字符串序列
>>> symbol.join(seq)
'I-love-China'
寫法2:省略對連接符號的定義,直接用
>>> seq=("I","love","China")
>>> '-'.join(seq)    
'I-love-China'
>>> 

將列表中的字符串合并成一個字符串:

>>> list=["I","love","China"]
>>> '-'.join(list)
'I-love-China'
>>> 

將字典中的鍵值進行連接:

>>> dict1={"a:1","b:2","c:3","d:4"}
>>> "-".join(dict1)
'c:3-d:4-b:2-a:1'
>>> 

PS:python中strip的使用

今天聊聊python去除字符串空格的函數:strip()和replace()

1.strip():

函數功能描述:Python strip() 方法用于移除字符串頭尾指定的字符(默認為空格或換行符)或字符序列。
注意:該方法只能刪除開頭或是結尾的字符,不能刪除中間部分的字符。
格式:str.strip([char])。其中,str為待處理的字符,char指定去除的源字符串首尾的字符。
返回結果:去除空格時候的新字符串。
示例:

	str = "00000003210Runoob01230000000"
	print str.strip( '0' ) # 去除首尾字符 0
	
	 結果:3210Runoob0123

	str2 = "   Runoob      "  # 去除首尾空格
	print str2.strip()
	
	結果:Runoob

2.replace()

函數功能描述:Python replace() 方法把字符串中的 old(舊字符串) 替換成 new(新字符串),如果指定第三個參數max,則替換不超過 max 次

格式:str.replace(old, new[, max]),參數在函數功能描述中已經說明。
返回值:返回字符串中的 old(舊字符串) 替換成 new(新字符串)后生成的新字符串,如果指定第三個參數max,則替換不超過 max 次。

示例:

str = "this is string example....wow!!! this is really string"
print str.replace("is", "was")
print str.replace("is", "was", 3)

結果:
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string

同樣可以采用replace實現空格的去除。舉個例:

	"  x y z  ".replace(' ', '')   # returns "xyz" 	

在這里插入圖片描述

原文鏈接:https://blog.csdn.net/qq_44985415/article/details/128702838

欄目分類
最近更新