I've just started learning to code Python today on Grok Learning and I'm currently stuck on this problem. I have to create a code that reads a message and:
I've done everything right but I can't get rid of a space at the end. I was wondering if anyone knew how to remove it. Here is my code:
code = []
translation = []
msg = input("code: ")
code = msg.split()
code.reverse()
for c in code:
if c[0].isupper():
translation.append(c)
print("says: ", end='')
for c in translation:
c = c.lower()
print(c, end = ' ')
Thank you:)
You need to iterate for all of the letters in translation
but the last and print it separately without the space:
for c in translation[:-1]:
c = c.lower()
print(c, end = ' ')
print(translation[-1], end='')
This is a common problem:
I'd say the pythonic way to do this, if you really want to build the resulting string, is str.join()
. It takes any iterable, for example a list, of strings, and joins all the elements together using the string it was called on as a separator. Take this example:
my_list = ["1", "2", "3"]
joined = ", ".join(my_list)
# joined == "1, 2, 3"
In your case, you could do
msg = "Hello hello test Test asd adsa Das"
code = msg.split()
code.reverse()
translation = [c.lower() for c in code if c[0].isupper()]
print("says: ", end='')
print(" ".join(translation))
# output:
# says: das test hello
For printing, note that print
can also take multiple elements and print them using a separator. So, you could use this:
print(*translation, sep=" ")
You could also leave out explicitly setting sep because a space is the default:
print(*translation)
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.