zoukankan      html  css  js  c++  java
  • python之字符串的分割和拼接

    关于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[,......]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略。

     5 >>> os.path.join('c:\', 'csv', 'test.csv')
     6 
     7 'c:\csv\test.csv'
     8 
     9 >>> os.path.join('windows	emp', 'c:\', 'csv', 'test.csv')
    10 
    11 'c:\csv\test.csv'
    12 
    13 >>> os.path.join('/home/aa','/home/aa/bb','/home/aa/bb/c')
    14 
    15 '/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")

    输出:

    *** *** ***
  • 相关阅读:
    istringstream、ostringstream、stringstream 类介绍 .
    istringstream、ostringstream、stringstream 类介绍 .
    Leading and Trailing(LightOJ
    欧拉函数(重要性质)
    UML——概述
    UML——用例视图
    JUnit——assertThat(acture,matcher)
    JUnit——Failure与Error
    JUnit——Annotation
    JUnit——运行多个测试方法
  • 原文地址:https://www.cnblogs.com/bangbangjiang/p/3380130.html
Copyright © 2011-2022 走看看