![](/img/trans.png)
[英]How do I differentiate between a string and a negative integer in python
[英]How do I differentiate between a tab and a space in a string in python
我正在尝试编写一个函数来查找字符串最常见的分隔符,它可以是逗号、空格或制表符。 我的问题是该函数不读取制表符,而是将它们作为一堆空格读取。 这是我的代码:
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"
如果您确定input_str
包含\\t
char,那么您的函数是正确的。
但是如果你的字符包含一个制表符,它将被解释为 4 个空格字符。 您的解决方法是使用input_str.count(" ")
计算空格的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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.