如何在Python中移除字符串中的换行和缩进?

2 投票
3 回答
4209 浏览
提问于 2025-04-17 15:09

在我的Python脚本中,有一个SQL语句写得很长,像这样:

query = """
    SELECT * FROM
        many_many
        tables
    WHERE
        this = that,
        a_bunch_of = other_conditions
"""

有没有什么好的方法可以把它变成一行?我试过这样做:

def formattedQuery(query):
    lines = query.split('\n')

    for line in lines:
        line = line.lstrip()
        line = line.rstrip()

    return ' '.join(lines)

这样做确实去掉了换行符,但缩进的空格却没有去掉。请帮帮我!

3 个回答

0

string.translate 可以用来删除字符(只需在第二个参数中提供 None,这样它就不会转换字符了):

import string
string.translate(query, None, "\n\t")
2

再来一行:

>>> import re

>>> re.sub(r'\s', ' ', query)

'SELECT * FROM many_many tables WHERE this = that, a_bunch_of = other_conditions'

这段代码的作用是把字符串 query 中的所有空白字符都替换成一个单独的空格 ' '

5

你可以这样做:

query = " ".join(query.split())

但是如果你的SQL查询中包含有空格或制表符的字符串(比如 select * from users where name = 'Jura X'),这样做就不太好用了。这是其他一些解决方案的问题,它们使用了 string.replace 或正则表达式。所以你的方法还不错,但代码需要修正。

其实你的函数有个问题 - 你返回的是原始值,而 lsplit 和 rsplit 的返回值被丢弃了。你可以这样修复它:

def formattedQuery(query):
  lines = query.split('\n')
  r = []

  for line in lines:
    line = line.lstrip()
    line = line.rstrip()
    r.append(line)

  return ' '.join(r) 

还有另一种做法:

def formattedQuery(q): return " ".join([s.strip() for s in q.splitlines()])

撰写回答