2.1.2

Strings

Test yourself

Strings

Strings are a special case of an array or list, where each element is a character. There are many methods we can apply to them:

Illustrative background for ConcatenationIllustrative background for Concatenation ?? "content

Concatenation

  • Concatenation is joining two strings together.
  • This can be done with the + sign. E.g:
    • "Hello " + "World" = "Hello World".
Illustrative background for Accessing a characterIllustrative background for Accessing a character ?? "content

Accessing a character

  • Remember, strings are just lists. So we can access a specific character in the exact same way as we access a list element:
    • string[3] would get the fourth character.
Illustrative background for Length of a stringIllustrative background for Length of a string ?? "content

Length of a string

  • The length of a string is given by the len function:
    • len("Hello") would give 5.
Illustrative background for SubstringsIllustrative background for Substrings ?? "content

Substrings

  • A substring is a part of a longer string.
  • In Python we take a substring using:
    • stringname[startPos:endPos]
  • This takes a substring starting at the 'startPos'th character, and finishing at the 'endPos'th character.

Jump to other topics

1Introduction to Python

2Data Structures

2.1Lists & Strings

2.2File Handling

3Modularity

3.1Subroutines

3.2Data Flow

4Good Practice

4.1Naming & Whitespace

4.2Comments

4.3Exceptions

Go student ad image

Unlock your full potential with GoStudent tutoring

  • Affordable 1:1 tutoring from the comfort of your home

  • Tutors are matched to your specific learning needs

  • 30+ school subjects covered

Book a free trial lesson