String Indexing and Slicing

String Indexing and Slicing

Indexing and slicing work on strings exactly as on lists. Each character has an index, starting at 0:

word = "Python"
print(word[0])
print(word[-1])
print(word[:3])
print(word[3:])

Output:

P
n
Pyt
hon

len gives the number of characters: len("Python") is 6. A space is a character like any other: len("a b") is 3.

One difference from lists: strings cannot be changed in place. word[0] = "J" is an error. To get a changed string, build a new one — slicing and concatenation both produce new strings:

word = "Python"
new_word = "J" + word[1:]
print(new_word)

Output:

Jython

Exercise

  1. Define a function named abbreviate with one parameter, word. It returns the first three characters.
  2. Define a function named last_character with one parameter, word. It returns the final character.

abbreviate("January") returns "Jan". last_character("Python") returns "n".

Run your code to see the output, then press Submit.

Tests

import unittest


class TestStringIndexingAndSlicing(unittest.TestCase):
    def test_abbreviate_january(self):
        self.assertEqual(abbreviate("January"), "Jan")

    def test_abbreviate_december(self):
        self.assertEqual(abbreviate("December"), "Dec")

    def test_last_character_of_python(self):
        self.assertEqual(last_character("Python"), "n")

    def test_last_character_of_a_single_letter(self):
        self.assertEqual(last_character("x"), "x")
def abbreviate(word):
    return word[:3]


def last_character(word):
    return word[-1]


print(abbreviate("January"))
print(last_character("Python"))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.