尝试检查字符串以进行逗号分隔。检查字符串后,我将使用它来帮助加载 SQL 数据库,这样字符串中的单词就不能用逗号以外的任何内容分隔。我确实有一种可行的方法,但对于 Python 来说似乎很笨拙。是否有更简洁/更便宜的方法来检查字符串以进行逗号分隔?
这是我在 Python 2.7.4 解释器中运行的尝试:
# List of possible Strings
comma_check_list = ['hello, world', 'hello world', 'hello, world',\
'hello world, good, morning']
# Dictionary of punctuation that's not a comma
punct_dict = {'@': True, '^': True, '!': True, ' ': True, '#': True, '%': True,\
'$': True, '&': True, ')': True, '(': True, '+': True, '*': True,\
'-': True, '=': True}
# Function to check the string
def string_check(comma_check_list, punct_dict):
for string in comma_check_list:
new_list = string.split(", ")
if char_check(new_list, punct_dict) == False:
print string, False
else:
print string, True
# Function to check each character
def char_check(new_list, punct_dict):
for item in new_list:
for char in item:
if char in punct_dict:
return False
# Usage
string_check(comma_check_list, punct_dict)
# Output
hello, world True
hello world False
hello, world False
hello world, good, morning False
预先感谢您的帮助!