String Operations

string = "This is my string"

  • Index of the first occurrence:
string.index("s")
# 3
  • How many occurrences of:
string.count("s")
# 3
  • Length:
len(string)
# 17
  • Starts with / ends with (produces a bool):
string.startswith("a") # False
string.endswith("g") # True
  • Upper/ Lowercase:
string.upper()
string.lower()

Slice

  • Slice, you can use negative numbers to count from the end of the string:
string[4:14]
# ' is my str'
  • Leave the first number blank to start at the beginning [:14]
  • Leave the last number blank to end at the end [4:]

  • Split a string into a list at a defined place:
string.split("m")
# ['this is ', 'y string']