What will be the output of the following Python code?

s = "Hello World"

s = s.split()

t = s.join("-")

print(t)

A) "Hello-World"

B) "H-e-l-l-o-W-o-r-l-d"

C) TypeError

D) None

Answer:

Answer by student

C) TypeError

Detailed answer by teachoo

  • The split() method is a built-in function that takes a string as an argument and returns a list of substrings that are separated by a delimiter. If no delimiter is specified, the default delimiter is whitespace. For example, s.split() returns [“Hello”, “World”].
  • The join() method is a built-in function that takes a list of strings as an argument and returns a string that is formed by joining the elements of the list with a separator. The separator is the string on which the join() method is called. For example, “-”.join([“Hello”, “World”]) returns “Hello-World”.

Let’s look at each option and see why they are correct or incorrect.

A) “Hello-World”

  • This option is incorrect because it does not match the output of the code. The code does not call the join() method on the string “-”, but on the list s, which is [“Hello”, “World”]. This causes an error because the join() method expects a string as a separator, not a list.

B) “H-e-l-l-o-W-o-r-l-d”

  • This option is incorrect because it does not match the output of the code. The code does not call the split() method on the string s, but on the list s, which is [“Hello”, “World”]. This causes an error because the split() method expects a string as an argument, not a list.

C) TypeError

  • This option is correct because it matches the output of the code. The code causes a TypeError because it tries to call the join() method on a list instead of a string. The error message is: TypeError: can only join an iterable

D) None

  • This option is incorrect because it does not match the output of the code. The code does not return None as the output, but raises an exception.

So, the correct answer is C) TypeError.

Go Ad-free
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh has done his B.Tech from Indian Institute of Technology, Kanpur. He has been teaching from the past 14 years. He provides courses for Maths, Science, Social Science, Physics, Chemistry, Computer Science at Teachoo.