Home  >  Article  >  Backend Development  >  python分割和拼接字符串

python分割和拼接字符串

WBOY
WBOYOriginal
2016-06-06 11:28:331152browse

关于string的split 和 join 方法
对导入os模块进行os.path.splie()/os.path.join() 貌似是处理机制不一样,但是功能上一样。

1.string.split(str=' ',num=string.count(str)):  以str为分隔,符切片string,如果num有指定值,则仅分隔num个子字符串。
S.split([sep [,maxsplit]]) -> 由字符串分割成的列表 返回一组使用分隔符(sep)分割字符串形成的列表。如果指定最大分割数,则在最大分割时结束。
如果分隔符未指定或者为none,则分隔符默认为空格。
注意:分隔符不能为空,否则会出错,但是可以有不含其中的分隔符。
os.path.split()
os.path.split是按照路径将文件名和路径分割开,比如d:\\python\\python.ext,可分割为['d:\\python', 'python.exe']

代码如下:


import os
 print os.path.split('c:\\Program File\\123.doc')
 print os.path.split('c:\\Program File\\')
 -----------------output---------------------
 ('c:\\Program File', '123.doc')
 ('c:\\Program File', '')


2.string.join(sep):  以string作为分割符,将sep中所有的元素(字符串表示)合并成一个新的字符串。
将join里字符串、元祖、列表的所有元素通过分隔符连接成一个新的字符串(字符串、元祖、列表它们是序列类型,有着相同的访问方式)
os.path.join(path1[,path2[,......]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略。

代码如下:


>>> os.path.join('c:\\', 'csv', 'test.csv')
'c:\\csv\\test.csv'
>>> os.path.join('windows\temp', 'c:\\', 'csv', 'test.csv')
'c:\\csv\\test.csv'
>>> os.path.join('/home/aa','/home/aa/bb','/home/aa/bb/c')
'/home/aa/bb/c'


例子:
写一个函数,参数为一个长字符串和一个word,将长字符串中是word的改为对应字母个数的**,比如,长字符串为“this hack is wack hack”,word为“hack”,那么要求函数输出:“this **** is wack ****”

代码如下:


def censor(text,word):
    texts = text.split(" ")
    for i in range(len(texts)):if texts[i] == word:
            texts[i] = "*" * len(word)
    return " ".join(texts)
print censor("hey hey hey","hey")


输出:
*** *** ***
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn