LearnWave
Learn it. Master it.

Strings

String operations

Slice a string to get any part of it.

Operations on strings:

  • Concatenation joins strings with +: 'Good' + 'Morning' is 'GoodMorning'. The original strings are not changed; a new string is made.
  • Repetition repeats a string with *: 'Ha' * 2 is 'HaHa'.
  • Membership checks whether one string is inside another: 'Indi' in 'Namaste India' is True; 'Delhi' in 'Namaste India' is False. not in gives the opposite answer.

Slicing takes out a part of a string. s[n:m] gives the characters from index n up to m - 1: it stops just before m, so it has m - n characters. For s = 'Namaste India':

  • s[0:7] is 'Namaste'.
  • A missing first index means 0, and a missing second index means to the end: s[8:] is 'India'.
  • An index too big is simply cut to the end of the string.
  • If n is greater than m, the result is an empty string ''.

A third value gives the step: s[0:7:2] takes every second character, giving 'Nmse'. Negative indices work too: s[-5:-1] is 'Indi'. And s[::-1] (a step of -1) reverses the string: 'aidnI etsamaN'.

str[n:m] stops just before m.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.