Python string.split()出现意外行为

Python string.split()出现意外行为,python,regex,whitespace,Python,Regex,Whitespace,假设我有一个字符串,string='a' 我执行string.split()并得到['a'] 我不想要这个,我只想要一个列表,当我的字符串中有空格时,alastring='abcd' 到目前为止,我已经尝试了以下所有方法,但都没有成功: >>> a = 'a' >>> a.split() ['a'] >>> a = 'a b' >>> a.split(' ') ['a', 'b'] >>> a = 'a'

假设我有一个字符串,
string='a'

我执行
string.split()
并得到
['a']


我不想要这个,我只想要一个列表,当我的字符串中有空格时,ala
string='abcd'

到目前为止,我已经尝试了以下所有方法,但都没有成功:

>>> a = 'a'
>>> a.split()
['a']
>>> a = 'a b'
>>> a.split(' ')
['a', 'b']
>>> a = 'a'
>>> a.split(' ')
['a']
>>> import re
>>> re.findall(r'\S+', a)
['a']
>>> re.findall(r'\S', a)
['a']
>>> re.findall(r'\S+', a)
['a', 'b']
>>> re.split(r'\s+', a)
['a', 'b']
>>> a = 'a'
>>> re.split(r'\s+', a)
['a']
>>> a.split(" ")
['a']
>>> a = "a"
>>> a.split(" ")
['a']
>>> a.strip().split(" ")
['a']
>>> a = "a".strip()
>>> a.split(" ")
['a']
我疯了吗?我在字符串“a”中没有看到空格

怎么了

编辑

FWIW,这就是我如何得到我所需要的:

# test for linked array
if typename == 'org.apache.ctakes.typesystem.type.textsem.ProcedureMention':
    for f in AnnotationType.all_features:
        if 'Array' in f.rangeTypeName:
            if attributes.get(f.name) and typesystem.get_type(f.elementType):
                print([ int(i) for i in attributes[f.name].split() ])

到此结束…

Split将始终返回一个列表,请尝试此操作

def split_it(s):
    if len(s.split()) > 1:
        return s.split()
    else:
        return s

split
的行为很有意义,它总是返回一个列表。为什么不检查列表长度是否为1

def weird_split(a):
    words = a.split()
    if len(words) == 1:
        return words[0]
    return words

您可以使用条件表达式检查是否存在空格,并且仅在检测到空格时使用
split

str1 = 'abc'
split_str1 = str1 if (' ' not in str1) else str1.split(' ')
print (split_str1)
str1 = 'ab c'
split_str1 = str1 if (' ' not in str1) else str1.split(' ')
print (split_str1)
这将产生以下输出:

abc
['ab', 'c']

split只返回一个列表。这就是问题所在。应用于字符串的方法
.split()
将始终返回该弹簧中所有子字符串的列表,并按空格分割(除非提供了另一个拆分字符)
'a'
有一个子字符串,即
'a'
,这就是列表中返回的内容
['a']
“当我的字符串中有空格时,我只想要一个列表”-这是个坏主意。处理始终是列表的结果要容易得多,而不是有时是字符串,有时是列表。按您要求的方式工作的
str.split
将是错误的主要来源。
.split()
始终返回一个列表,即使没有拆分字符串,这可能是更一致的行为。看,你陷入了一个普通的新手陷阱,你认为“如果这个操作的结果只是一个[东西]而不是[东西]的[容器],而只有一个[东西],那么我不必把[东西]从[容器]中拿出来,这不是更容易吗”,但事实上,没有一致的返回类型意味着您必须编写更多的代码来有条件地使用单个对象或对象容器。事实上,不管怎样,你通常会把一件东西放在一个容器里,这是处理这两种情况最简单的方法。谢谢!这是漫长的一天。我想是时候辞职了!哎呀!NP你投了那么多球,得10分,看起来很累人。我的情况更糟。需要确定XMI注释/标记中的特征/属性是否是数组的表示形式。这只是周一的脑死亡综合症。@horcle_buzz:这似乎是一个不好的检查方法。毕竟,您的属性可以是恰好只有一个元素的数组的表示形式。实际上,我有它。我使用的数据结构(UIMA CAS)具有已定义的类型系统定义文件。我可以在类型系统文件中搜索属于数组的属性/功能!谢谢@user2357112让我想得更深一点。
abc
['ab', 'c']