gpt4 book ai didi

python - 将 Python 中的 '*' 字符读入新字符串时出现问题

转载 作者:行者123 更新时间:2023-12-01 09:12:52 25 4
gpt4 key购买 nike

我正在尝试删除 SQL 文本中的多行 SQL 注释并执行其余语句。结果应该是一个新字符串,省略了所有多行 SQL 注释。

但是,当从 SELECT 语句中读取 '*' 字符时,会导致打印的输出字符串不正确。从逻辑上讲,这没有任何意义。想知道这个角色是否存在任何已知的 Python 错误?

#sql = "actual sql code goes here; \n /*comment #1*/ more sql code would go 
#here; \n more renditions of SQL code here; \n /*comment #2*/ SELECT*FROM
#TABLE;"

sql = "SELECT* FROM TABLE a WHERE THIS TRUE"

sql_2 = ""
flag = True

try:

for index, character in enumerate(sql):
while (flag):
if character != r'/' and sql[index + 1] != r'*':
sql_2 += character
flag = True
break
else:
flag = False

if (character == r'*' and sql[index + 1] == r'/'):
flag = True

elif (character == r'/' and sql[index - 1] == r'*'):
flag = True

except IndexError:
if character != r'/':
sql_2 += character

print(sql_2)

预期输出:'SELECT* FROM TABLE a WHERE THIS TRUE'

实际输出:'SELEC'

最佳答案

import re

sql = "actual sql code goes here; \n /*comment #1*/ more sql code would go here; \n more renditions of SQL code here; \n /*comment #2*/ SELECT*FROM TABLE;"

re.sub(r'/[*].*[*]/', '', sql)

# Output =>
# 'actual sql code goes here; \n more sql code would go here; \n more renditions of SQL code here; \n SELECT*FROM TABLE;'

关于python - 将 Python 中的 '*' 字符读入新字符串时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51505242/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com