Python 中的join()与split()

来源:互联网 发布:阿里云学生认证学信网 编辑:程序博客网 时间:2024/05/12 11:13

1. join()

1. join()的介绍

join()string模块提供的一个方法,用于将序列中的元素以指定的字符连接生成一个新的字符串。因此它需要两个参数,一个是words,另一个是分隔符seq ,string.join(words,seq)

2. Code

#1)对序列进行操作LIST =["I","am","bigship","come","from","China"]print string.join(LIST," ")print ' '.join(LIST)#2)对字符串进行操作str="i am bigship"print string.join(str,"->")print '->'.join(str)#3)对元组进行操作TUPLE = ("I","am","bigship","come","from","China")print string.join(TUPLE," ")print ' '.join(TUPLE)#4)对字典进行操作Dir ={'b':1,'i':2,'g':3,'s':4,'h':5,'p':7}print string.join(Dir,':')print ':'.join(Dir)

3. Input/Output

I am bigship come from ChinaI am bigship come from Chinai-> ->a->m-> ->b->i->g->s->h->i->pi-> ->a->m-> ->b->i->g->s->h->i->pI am bigship come from ChinaI am bigship come from Chinab:g:i:h:p:sb:g:i:h:p:s

2. split()

1. split()的简单介绍

split():拆分字符串。通过指定分隔符对字符串进行切片,并返回分割后的字符串列表list,语法str.split(seg="",num=string.count(seg))[n]

  • 分隔符seg默认为空格.
  • num表示分割的次数,默认为seg的个数,可以形成num+1个切片.
  • [n]表示选取第n个切片

2. Code

str = "welcome to Harbin, it's a beautiful place"print str.split(' ')print str.split()print str.split(' ',3)print str.split(' ')[2]

3. Input/Output

['welcome', 'to', 'Harbin,', "it's", 'a', 'beautiful', 'place']['welcome', 'to', 'Harbin,', "it's", 'a', 'beautiful', 'place']['welcome', 'to', 'Harbin,', "it's a beautiful place"]Harbin,
1 0
原创粉丝点击