如何区分制表符和python字符串中的空格

问题描述 投票:2回答:1

我正在尝试编写一个函数,该函数查找字符串的最常见分隔符,它可以是逗号,空格或制表符。我的问题是该函数不读取选项卡,而是将它们读取为一堆空格。这是我的代码:

def which_delimiter(input_str):

    # count total number of spaces, commas and tabs in the string
    spaces = input_str.count(" ")
    commas = input_str.count(",")
    tabs = input_str.count("\t")

    # return the delimiter with the highest frequency
    # if there is none, raise an error
    if spaces == 0 and commas == 0 and tabs == 0:
        raise AssertionError
    elif spaces > commas and spaces > tabs:
        return "spaces"
    elif commas > spaces and commas > tabs:
        return "commas"
    else:
        return "tabs"
python string whitespace delimiter delimiter-separated-values
1个回答
0
投票

如果您确定input_str包含\t字符,则您的功能正确。

但是如果char包含一个制表符,它将被解释为4个空格字符。一种解决方法是使用input_str.count(" ")

计算一堆空格

哪个给出:

def which_delimiter(input_str):

    # count total number of spaces, commas and tabs in the string
    spaces = input_str.count(" ")
    commas = input_str.count(",")
    tabs = input_str.count("\t")
    bunch_spaces = input_str.count("    ")

    # You can count tabs and bunch spaces separately or regroup them, using for example
    # tabs_total_count = tabs + bunch_spaces.
    # Then you use your if/elif statements as you want with above elements.
© www.soinside.com 2019 - 2024. All rights reserved.