[转载] python字符串分割

参考链接: Python字符串| strip

常用strip()去除字符串string首尾空格,在用split(‘XX’)将字符串string分成字符串列表。 

e.g: 

 

>>> s1 = '   123||456ab||789||  kd290b  ' * 2

>>> print s1

   123||456ab||789||  kd290b     123||456ab||789||  kd290b  

>>> def separate_string(string,spl = '||'):

    string = string.strip()

    slst = string.split(spl)

    for s in slst:

        s = s.strip()

        if s.isalnum():

            print s

        else:

            print 'String illegal!'

 

            

>>> separate_string(s1)

123

456ab

789

String illegal!

456ab

789

kd290b

>>> stemp = s1.strip()

>>> print stemp

123||456ab||789||  kd290b     123||456ab||789||  kd290b

>>> stemplist = stemp.split('||')

>>> print stemplist

['123', '456ab', '789', '  kd290b     123', '456ab', '789', '  kd290b']

>>> 

>>> s2 = '    1sd*q564 *2349d*   jh588  *   we890 *3dfghl  '

>>> separate_string(s2,'*')

1sd

q564

2349d

jh588

we890

3dfghl

         不用split()函数,用c++习惯去除空格分割字符串:

 

 

 

>>> s3 = '  uidd    3fg 23fd    rflkd  6ykpld     9dfghkotr    '

>>> def strip_space(string):

    string = string.strip()

    pos_start = string.find(" ")

    print string[:pos_start]  #the first ftring

    pos_end = pos_start

    while pos_end <= len(string) and pos_end != -1:

        while " " == string[pos_start]:

            pos_start = pos_start + 1

        pos_end = string.find(" ",pos_start)

        if -1 != pos_end:

            print string[pos_start:pos_end]

        else:

            print string[pos_start:]

        pos_start = pos_end

 

        

>>> strip_space(s3)

uidd

3fg

23fd

rflkd

6ykpld

9dfghkotr

>>>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值