A string is a row of letters
Text in Python is called a string. Each letter has a position number, and counting starts at 0, not 1.
word = "PYTHON"
print(word[0]) # First letter
print(word[5]) # Last letter
print(word[-1]) # Also the last letter
print(len(word)) # How many lettersOutput
P N N 6
Slicing: cutting out a piece
word[start:stop] gives the letters from start up to, but not including, stop.
word = "PYTHON"
print(word[0:3]) # PYT
print(word[2:]) # From position 2 to the end
print(word[:2]) # From the start to position 2
print(word[::-1]) # BackwardsOutput
PYT THON PY NOHTYP
Useful string methods
text = " Machine Learning is fun "
print(text.strip()) # Remove spaces at the ends
print(text.upper())
print(text.lower())
print(text.replace("fun", "useful"))
print(text.strip().split(" ")) # Break into a list of words
print("Learning" in text) # Is this inside?Output
Machine Learning is fun MACHINE LEARNING IS FUN machine learning is fun Machine Learning is useful ['Machine', 'Learning', 'is', 'fun'] True
| Method | What it does |
|---|---|
| .strip() | Removes spaces from both ends |
| .upper() / .lower() | Changes the case |
| .replace(a, b) | Swaps a for b |
| .split(x) | Breaks text into a list at x |
| .count(x) | Counts how many times x appears |
| .startswith(x) | Checks how the text begins |
Code challenge
Reverse the word “Namaste” and print it.
print("Namaste"[::-1])
Count how many times “a” appears in “banana”.
print("banana".count("a")) gives 3.
Finished reading?