繁体   English   中英

如何在 python 中的 for 循环 function 的最后删除空格/跳转到下一行

[英]How can I remove the space/ jump to the next line at the last of a for loop function in python

问题在问题中说明。 谢谢

'''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='')

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

摆弄您的代码后,我得到以下信息:

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="")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM