码迷,mamicode.com
首页 > 编程语言 > 详细

python中split()和split(' ')的区别

时间:2017-08-16 18:24:18      阅读:444      评论:0      收藏:0      [点我收藏+]

标签:res   log   int   杂志   新员工   空格   bsp   end   class   

总结:split()的时候,多个空格当成一个空格;split(‘ ‘)的时候,多个空格也要分割,会分割出来空。

例1:

牛客网:牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?

这样的代码就可以通过:

s=‘student a am I‘
s=‘ ‘       
if not s :
    print(s)
s=s.split(‘ ‘)
        
result=[]
for i in range(len(s)-1,-1,-1):
    result.append(s[i])
    if i:#最后一个位置不需要加空格
        result.append(‘ ‘)
m=‘‘.join(result)
length=(len(m))
print(m)
print(length)

输出:

 
1

 

如果把split(‘ ‘)中的空格去掉,就处理不了输入为空的情况:

s=‘student a am I‘
s=‘ ‘       
if not s :
    print(s)
s=s.split()
        
result=[]
for i in range(len(s)-1,-1,-1):
    result.append(s[i])
    if i:#最后一个位置不需要加空格
        result.append(‘ ‘)
m=‘‘.join(result)
length=(len(m))
print(m)
print(length)

输出:

0

例2:

用split()测试一下看看:

s0=‘we are students‘#一个空格
s1=‘we are  students‘#两个空格
s2=‘we are   students‘#三个空格
s3=‘we are    students‘#四个空格

s0=s0.split()
print(s0)
print(len(s0))
s1=s1.split()
print(s1)
print(len(s1))
s2=s2.split()
print(s2)
print(len(s2))
s3=s3.split()
print(s3)
print(len(s3))

输出为:

[‘we‘, ‘are‘, ‘students‘]
3
[‘we‘, ‘are‘, ‘students‘]
3
[‘we‘, ‘are‘, ‘students‘]
3
[‘we‘, ‘are‘, ‘students‘]
3

 

用split(‘ ‘)测试一下看看:

s0=‘we are students‘#一个空格
s1=‘we are  students‘#两个空格
s2=‘we are   students‘#三个空格
s3=‘we are    students‘#四个空格

s0=s0.split(‘ ‘)
print(s0)
print(len(s0))
s1=s1.split(‘ ‘)
print(s1)
print(len(s1))
s2=s2.split(‘ ‘)
print(s2)
print(len(s2))
s3=s3.split(‘ ‘)
print(s3)
print(len(s3))

输出:

[‘we‘, ‘are‘, ‘students‘]
3
[‘we‘, ‘are‘, ‘‘, ‘students‘]
4
[‘we‘, ‘are‘, ‘‘, ‘‘, ‘students‘]
5
[‘we‘, ‘are‘, ‘‘, ‘‘, ‘‘, ‘students‘]
6

总结:split()的时候,多个空格当成一个空格;split(‘ ‘)的时候,多个空格也要分割,会分割出来空。

python中split()和split(' ')的区别

标签:res   log   int   杂志   新员工   空格   bsp   end   class   

原文地址:http://www.cnblogs.com/shixisheng/p/7374642.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!