简体   繁体   中英

Looping and Lists - Grok Learning

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:

  • read the words in reverse order
  • only take the words in the message that start with an uppercase letter
  • make everything lowercase

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:

  • You have a sequence of n elements
  • You want to format them in a string using a separator between the elements, resulting in n-1 separators

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)

You can simply use join() and f-strings .

result = ' '.join(translation).lower()
print(f"says: {result}")

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.

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