-4

If a user inputs a string "Hello world"
how can i get an output list to look like ["Hello", "world"]
instead of ['H','e','l','l','o',' ','w','o','r','l','d']
Whats an efficient way to do this?

I used a for loop, and omitted the whitespace but my output does not include the last character

def reverse_string(x):
    reversed_list= []
    temp_string = ""
    count= 0
    for i in x:
        if i == " " or i == x[-1]:
            reversed_list.insert(count, temp_string)
            temp_string = ""
            count+=1
            continue
        temp_string += i

my output: ['Hello', 'worl']

sorry if this is a repost

1 Answers1

1

Use split().

Example.

x = "Hello world"
x.split( )

Please add any character you want to split at if you want to split on whitespace use like this

x.split(" ")
Jaskaran Singh
  • 531
  • 3
  • 14
Gilseung Ahn
  • 2,598
  • 1
  • 4
  • 11