AnyCompiler

Strings and String Methods

A string is just text, and Python treats it as a sequence of characters — which means you can index into it and slice it the same way you would a list.

greeting = "Hello, World!"
print(greeting[0])
print(greeting[7:12])
print(greeting.upper())
print(greeting.lower())
print(len(greeting))
Output
H
World
HELLO, WORLD!
hello, world!
13
  • greeting[0] gets the character at index 0 — Python indexes from 0, not 1
  • greeting[7:12] is a slice — characters from index 7 up to (not including) index 12
  • .upper() and .lower() return a new string, they don't change the original
  • len() works on strings the same way it works on lists

f-strings — the modern way to build text

You'll constantly need to combine variables with fixed text. f-strings (prefix the string with f) let you drop a variable straight into a string using curly braces, instead of clumsily concatenating pieces with +.

name = "Abhimanyu"
age = 25
print(f"My name is {name} and I am {age} years old.")
Output
My name is Abhimanyu and I am 25 years old.

Splitting and replacing

.split() breaks a string into a list wherever it finds the separator you give it. .replace() swaps out one substring for another, everywhere it appears.

sentence = "Python is fun"
words = sentence.split(" ")
print(words)
print(sentence.replace("fun", "powerful"))
Output
['Python', 'is', 'fun']
Python is powerful

Next: lists — Python's core way of storing an ordered collection of values.

Practice exercise

Create text = "Hello, World!". Print just the word "World" using slicing.