String Data Structure
A
string
is a data type thats represented by an array of characters.In Python, each character follows the unicode standard, which is a standardized list of characters (including emojis).
Strings are immutable, which means they cannot be modified.
So unlike arrays, updating a position in a string is not allowed:
Immutability also implies that some Pythonic operations, such as string concatenation, actually allocates new memory to create the resulting concatenated string.
Since using
+
to concatenate strings is costly, it's often better to operate on an array instead, and use join at the end.Under the hood, Python's
join
allocates a mutable bytearray, and updates each position with the byte representation of each character, including those of the separator, before converting back into a string.Therefore, Python's
join
concatenates strings in linear time.Useful Python String Functions
1. ord()
Use
ord
to convert a unicode character into its unicode code.Python's
ord
is often useful to represent characters as integers, or access a character that is a specific distance away from another character.2. chr()
Opposite of ord, use
chr
to convert an integer that represents a unicode code to its unicode character.6 Essential Strings Coding Interview Problems
Master Strings by trying the coding challenges below.
- 1.Reverse StringEasy
- 2.AnagramEasy
- 3.Reverse wordsMedium
- 4.String matchMedium
- 5.CompressionMedium
- 6.One edit awayHard