如何让Python的split()同时支持空格与逗号两种输入分隔方式?
同时支持空格/逗号分隔输入的解决方案
方法一:替换逗号为空格后分割
先把输入里的所有逗号替换成空格,再用默认的split()方法分割——split()会自动处理任意数量的空白符,不管用户用纯逗号、纯空格还是混合格式,都能正确拆分出身高数值。
代码示例:
student_heights = input("Input a list of student heights ").replace(',', ' ').split() for n in range(len(student_heights)): student_heights[n] = int(student_heights[n])
方法二:用正则表达式匹配多种分隔符
如果需要更精准处理(比如用户输入170,180 165这种无空格的逗号分隔),可以用re.split()匹配逗号(可带后续空格)或空格作为分隔符,同时过滤掉可能出现的空字符串(比如输入末尾带分隔符的情况)。
代码示例:
import re # 匹配逗号(可跟任意空格)或任意数量的空格作为分隔符 input_str = input("Input a list of student heights ") student_heights = re.split(r',\s*|\s+', input_str) # 过滤空字符串后转整数 student_heights = [int(height) for height in student_heights if height]
两种方法各有优势:第一种无需额外导入模块,代码简洁;第二种能覆盖更多复杂输入场景,容错性更强。
内容的提问来源于stack exchange,提问作者Haris Bade
相关产品推荐
相关产品推荐

