KnowledgeBoat Logo

Computer Science

Consider the string mySubject:

mySubject = "Computer Science"

What will be the output of:

  1. print(mySubject[:3])
  2. print(mySubject[-5:-1])
  3. print(mySubject[::-1])
  4. print(mySubject*2)

Python String Manipulation

2 Likes

Answer

  1. Com
  2. ienc
  3. ecneicS retupmoC
  4. Computer ScienceComputer Science

Explanation

  1. The slice mySubject[:3] takes characters from the start ('C') of the string up to index 2 ('m') and prints it.
  2. The code print(mySubject[-5:-1]) uses negative indexing to slice the string. It starts from the fifth character from the end ('i') and ends before the last character ('c'), outputting ienc.
  3. The code print(mySubject[::-1]) reverses the string using slicing. The [::-1] notation means to start from the end and move backwards, outputting ecneicS retupmoC.
  4. When an integer is multiplied by a string in Python, it repeats the string the specified number of times. Hence, the code print(mySubject*2) repeats the string stored in mySubject twice.

Answered By

3 Likes


Related Questions