The problem is stated in the question. Thanks
'''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↵
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="")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.