[英]How can I remove the space/ jump to the next line at the last of a for loop function in python
The problem is stated in the question.问题在问题中说明。 Thanks
谢谢
'''def=ABC ''' '''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='')
I expect the output of it to be ABC, but the actual output is ABC↵我希望它的 output 是 ABC,但实际的 output 是 ABC↵
After fiddling with your code, I got the following:摆弄您的代码后,我得到以下信息:
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='')
The code above is a mess, but it shows you some alternatives to what you originally were doing.上面的代码是一团糟,但它向您展示了您最初所做的一些替代方案。
In the end, I recommend this:最后,我推荐这个:
import string导入字符串
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.