如何删除空格/跳转至python中for循环函数的最后一行的下一行

问题描述 投票:0回答:1

问题已在问题中阐明。谢谢

'''def = ABC'''

import string

text=input('String: ')

y=[]

z=[]

m=[]

for i in text:

    if i in string.punctuation:

        y.insert(0,i)

    elif i in string.whitespace:

        y.insert(0,i)

    else:

        z.insert(0,i)

for k in z:

    m.insert(0,k)

for k in m:

    print(k, end='')

我希望它的输出是ABC,但实际输出是ABC↵

python python-3.x
1个回答
0
投票

在摆弄了您的代码之后,我得到了以下内容:

import string

is_punc = lambda ch, chs=string.punctuation:\
    ch in chs

is_white = lambda ch, chs=string.whitespace:\
    ch in chs

is_p_or_w = lambda ch, isw=is_white, isp=is_punc:\
    isw(ch) or isp(ch)

is_not_pw = lambda ch, ispw=is_p_or_w:\
    not ispw(ch)

text=input('String: ')

# `y` is a list of whitespace and punctuation
# characters from text.
# Duplicates are included. e.g. [".", ":", ".", "."]
# In list `y` chars appear in the reverse order
# of where they appeared in `text`

y = list(reversed(list(filter(is_p_or_w, text))))
z = list(reversed(list(filter(is_not_pw, text))))

# m = []
# for k in z:
#     m.insert(0,k)
m = list(reversed(z))

# `m` is a copy of `text` with
# all of the punctuation and white-space removed

for k in m:
    print(k, end='')

上面的代码是一团糟,但是它向您展示了一些您最初所做的选择。

最后,我建议这样做:

导入字符串

def remove_whitespace_and_punc(stryng):
    output = list()
    for ch in stryng:
        if ch in string.whitespace or ch in string.punctuation:
            ch = ""
        output.append(ch)
    return "".join(output)

text = input('String: ')
clean_text = remove_whitespace_and_punc(text)
print(clean_text, end="")
© www.soinside.com 2019 - 2024. All rights reserved.