Python 我怎样才能去掉f字符串中的空格?
我有一个带有if语句的f字符串,但当I值设置为false时,它会留下一个空格?这是我的Python 我怎样才能去掉f字符串中的空格?,python,Python,我有一个带有if语句的f字符串,但当I值设置为false时,它会留下一个空格?这是我的 from sqlalchemy.schema import DDLElement from sqlalchemy.sql import table from sqlalchemy.ext import compiler class CreateView(DDLElement): def __init__(self, name, selectable, replace=True):
from sqlalchemy.schema import DDLElement
from sqlalchemy.sql import table
from sqlalchemy.ext import compiler
class CreateView(DDLElement):
def __init__(self, name, selectable, replace=True):
self.name = name
self.selectable = selectable
self.replace = replace
@compiler.compiles(CreateView)
def complile_create_view(element, compiler, **kwargs):
replace_text = "OR REPLACE"
return (
f"""CREATE {replace_text if element.replace else ''} VIEW {element.name} """
f"""AS {compiler.sql_compiler.process(element.selectable, literal_binds=True)}"""
)
要在我的终端上进行测试
from sqlalchemy import text
view_query = text("SELECT * FROM my_table")
create_view = CreateView('my_view', view_query, replace=False)
In [62]: print(str(create_view.compile()))
CREATE VIEW my_view AS SELECT * FROM my_table
如果我设置replace=True,我的DDL就可以了。如何消除创建和查看之间的额外空间?我可以想到两个选项: 第一个选项是从字符串中取出空格并将其添加到替换项中:
f"CREATE{' ' + replace_text if element.replace else ''} VIEW {element.name}"
显然有点难看。或在格式化后使用单个空格放置两个空格:
f"CREATE {replace_text if element.replace else ''} VIEW {element.name}".replace(' ', ' ')
如果您不使用replace_text,则会发生这种情况,因此只需将空格移动到其值,然后将
else
更改为输出空格,而不是空:
@compiler.compiles(CreateView)
def complile_create_view(element, compiler, **kwargs):
replace_text = " OR REPLACE "
return (
f"""CREATE{replace_text if element.replace else ' '}VIEW {element.name} """
f"""AS {compiler.sql_compiler.process(element.selectable, literal_binds=True)}"""
)
为什么这很重要?它仍然有效。如果您遇到错误,那不是因为额外的空间。是的,DDL是有效的,因为sql仍将处理它,我只希望它是完美的。如果您希望它是完美的,您不会使用像这样的
f
字符串来构建字符串。我的SQL注入感觉有些刺痛,但我不能给出一个具体的例子。没错,我可以用另一种方式构建字符串,我只是想看看我是否可以。看看答案,这完全是丑陋的。我想不出一个合理的方案来要求这样做。这并不是说他们错了,但我只是看不出通过这个解决了什么问题。这将导致创建后没有空间。例如,如果replace\u text='foo'
,您将获得CREATEfooVIEW…
,而这项功能正常工作时,这似乎是一种绝对会杀死5年后试图维护它的人的事情。我注意到并引用了replace\u text
周围的必填空格。啊,可怜的实习生。也许在return语句之前,在replace_文本周围单独添加空格