Python 中的join()与split()

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 China
I am bigship come from China
i-> ->a->m-> ->b->i->g->s->h->i->p
i-> ->a->m-> ->b->i->g->s->h->i->p
I am bigship come from China
I am bigship come from China
b:g:i:h:p:s
b: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,

你可能感兴趣的:(JOIN,python,split)