问题已在问题中阐明。谢谢
'''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↵
在摆弄了您的代码之后,我得到了以下内容:
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="")