python中split()函数的用法详解

一、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

%s 个评论

要回复文章请先登录注册