A string is an inmutable sequence of characters. This post covers string operations, including iteration, slicing, concatenation, comparison, string methods, and functions.
text = 'abc' letter = text[0]
Iteration
text = 'abc'
for letter in text:
print(letter)
Slicing
The start index is inclusive; the end index is exclusive.
If the end index goes beyond the end of the string, python will stop at the end of the string without throwing an error.
text = 'abcdef' print(text[0:4]) --abcd print(text[:4]) --abcd print(text[4:10]) --ef print(text[4:]) --ef print(text[:]) --abcdef
Concatenation
a = 'Hello ' b = a + 'there' print(b) --Hello there
Contains Substring
text = 'abcd' found = 'bc' in text print(found) --True
String Comparison
if first == second:
print('Same string')
if first < second:
print('First comes before second')
if first > second:
print('First comes after second')
String Library
text = 'abcd'
upper = text.upper()
lower = upper.lower()
text.capitalize()
text.center(width)
text.center(width, fillChar)
text.strip()
text.lstrip()
text.rstrip()
text.endswith(suffix)
# Returns starting position if found or -1 if not found
text.find('bc')
text.find(something, startingIndex)
# Replaces all instances if there is no count argument
text.replace(oldstr, newstr)
text.replace(oldstr, newstr, count)
Functions
- len(text): Length of a string
- type(text): Class type of text, which will return <class ‘str’> for a string
- dir(text): Returns a list of methods in the str class