代码之家  ›  专栏  ›  技术社区  ›  horcle_buzz

string.split()出现意外行为

  •  -3
  • horcle_buzz  · 技术社区  · 6 年前

    假设我有一根绳子, string = 'a'

    我愿意 string.split() ['a']

    string = 'a b c d'

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

    >>> 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”中没有看到空格。

    >>> r"[^\S\n\t]+"
    '[^\\S\\n\\t]+'
    >>> print(re.findall(r'[^\S\n\t]+',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() ])
    

    3 回复  |  直到 6 年前
        1
  •  2
  •   Rustang    6 年前

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

    def split_it(s):
        if len(s.split()) > 1:
            return s.split()
        else:
            return s
    
        2
  •  1
  •   nico    6 年前

    行为 split 有道理,它总是返回一个列表。为什么不检查列表长度是否为1?

    def weird_split(a):
        words = a.split()
        if len(words) == 1:
            return words[0]
        return words
    
        3
  •  0
  •   fountainhead    6 年前

    可以使用条件表达式检查是否存在空格,并使用 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']