0

This is an assignment where we have to take a sentence or phrase as input and output the phrase without whitespace.

Example: if input is 'hello there' output would be 'hellothere'

the code I have so far only outputs the string in separate letters: Like 'h', 'e', 'l', etc etc

def output_without_whitespace(input_str):
   lst = []
   for char in input_str:
       if char != ' ':
           lst.append(char)
   return lst

if __name__ == '__main__':
   phrase = str(input('Enter a sentence or phrase:\n'))
   print(output_without_whitespace(phrase))

3 Answers3

0

You've almost got it. You just need to join the list into a string.

print(''.join(output_without_whitespace(phrase)))

You could replace the loop in your function with a list comprehension.

def output_without_whitespace(input_str):
   return [ch for ch in input_str if ch != ' ']

That will return the same list your implementation does.

If you want your function to return a string, we can use the same join from before:

def output_without_whitespace(input_str):
   return ' '.join([ch for ch in input_str if ch != ' '])

But if we're doing that, we don't really need to pass a list to join. Instead we can use a generator expression.

def output_without_whitespace(input_str):
   return ' '.join(ch for ch in input_str if ch != ' ')

As others have pointed out, all of this is overkill if we just use replace.

def output_without_whitespace(input_str):
   return input_str.replace(' ', '')
Chris
  • 26,361
  • 5
  • 21
  • 42
0
def output_without_whitespace(input_str):
   str1=input_str.replace(" ","")
   return str1
   

if __name__ == '__main__':
   phrase = str(input('Enter a sentence or phrase:\n'))
   print(output_without_whitespace(phrase))
justjokingbro
  • 169
  • 2
  • 13
0
def output_without_whitespace(phrase):
    return phrase.replace(" ", "")

if __name__ == '__main__':
    phrase = str(input('Enter a sentence or phrase:\n'))
    print(output_without_whitespace(phrase))

Reference: https://stackoverflow.com/a/8270146/17190006

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 20 '21 at 03:35