簡體   English   中英

Python - 從字符串中刪除空格和縮進

[英]Python - remove spaces and indents from string

我有一個 sql 查詢字符串

query_for_update = 
f'''
update {db_name}.{schema_name}.{self.table_name}
set {self.updated_field} = {self.updated_field}
where {self.key_field} in ({ids});
'''

但是當我嘗試將此查詢寫入文件f.write(query_for_update)時,我得到以下結果:

update store_1.dbo.[my_table]
            set [Trusted Plan] = [Trusted Plan]
            where [Entry No_] in (1472371,
1472375,
1472377,
1472379,
1472373,
);

創建字符串的代碼:

ids_string = ',\n'.join(["'" + str(item) + "'" for item in result.id])
query_for_update = mssql_table.get_update_query('dbo', mssql_db_name, ids_string).strip()
with open(mssql_server_name + '.sql', 'a') as f:
    f.write(query_for_update)

在這種情況下,如何刪除字符串的縮進?

您可以使用textwrap.dedent (標准庫):

import textwrap

query = textwrap.dedent(f"""\
    update {db_name}.{schema_name}.{self.table_name}
    set {self.updated_field} = {self.updated_field}
    where {self.key_field} in ({ids});
""")

print(query)

這將刪除每行之間共有的所有前導空格。 用於tipple 引用的字符串。

您可以使用帶有 for 循環的str.strip()函數來修復它。

for x in list: 

  if x.strip():

    list2.append(x)

那么您可以使用 list2 作為新的可用列表

您可以使用str.stip方法https://www.w3schools.com/python/ref_string_strip.asp

對於縮進和中斷,您需要考慮可能需要使用\n textwrap 庫中還有一個dedent方法,您可能會感興趣。 https://docs.python.org/3/library/textwrap.html

我希望這有幫助 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM