Strings

Lesson Progress
0% Complete

A Python string is a collection of text, stored as a sequence of individual characters. Strings are written between either single or double quotation marks, like 'hello' or "world".

Functions Overview

Properties

Return a value

  • len(s)
  • s.find(x)

Tests

True/False

  • x in s
  • s.isalpha()
  • s.isdigit()
  • s.isspace()
  • s.startswith(x)
  • s.endswith(x)

Modifiers

Return a string

  • s.upper()
  • s.lower()
  • s.strip()
  • s.replace(x, y)
  • s.format(a, b, ...)
  • s[start:end]
  • s.split(x)
  • x.join(lst)

len(s) – returns a number of characters in string

s.find(x) – returns index of substring

Searches left-to-right through string s. Returns index of first occurrence of substring x if found, otherwise -1.

>>> s = 'Python'
>>> s.find('y')
1
>>> s.find('tho')
2
>>> s.find('xx')
-1

in – test if substring appears in a string

>>> 'Dog' in 'CatDogBird'
True
>>> 'dog' in 'CatDogBird'
False
>>> 'd' in 'CatDogBird'
True
>>> 'x' in 'CatDogBird'
False

s.startswith(x) – True if s begins with substring x

s.endswith(x) – True if s ends with substring x

s.upper() – converts all chars in string to uppercase

s.lower() – converts all chars in string to lowercase

s.split(x)s split into list by char x

Divides string s into list of parts. New item specified by separator x.

>>> 'a,b,c'.split(',')
['a', 'b', 'c']
>>> 'a:b:c'.split(':')
['a', 'b', 'c']

Double separator causes an empty string.

>>> 'a::b'.split(':')
['a', '', 'b']

x.join(lst) – list lst as a string, with x between lines

String Challenges

Loading Challenge
Pass Fail Error
Loading Challenge
Pass Fail Error
Loading Challenge
Pass Fail Error
Loading Challenge
Pass Fail Error
Loading Challenge
Pass Fail Error