✍️
Coding🔬 Ages 11-13Beginner 9 min read

Working with Text and Strings

Learn how to work with text and strings in Python: create strings, join them, slice them, change case, find and replace, and format messages. Runnable code, a worked example and a quiz.

Key takeaways

  • A string is text wrapped in quotes, like "hello" or 'cat'
  • You join strings with + and repeat them with *
  • Each character has a position (index) starting at 0
  • String methods like .upper() and .replace() give you new, changed strings
  • f-strings let you drop variables straight into a message

What is a string?

When you tell a computer to store text — a name, a message, a password, a whole story — that text is called a string. A string is simply a row of characters (letters, numbers, spaces and symbols) wrapped in quotation marks.

greeting = "Hello there"
animal = 'cat'
print(greeting)
print(animal)

Line by line:

  • greeting = "Hello there" stores the text Hello there in a box (a variable) named greeting.
  • animal = 'cat' stores cat. Notice you can use single ' or double " quotes — both are fine, as long as they match.
  • The two print() lines display the contents on the screen.

The quotes are not part of the string. They are just signposts telling Python "the text starts here and ends here." If you printed 42 without quotes you'd get the number forty-two; print "42" and you get the text four-two, which behaves very differently. If you're new to storing data, the lesson on variables is a good warm-up.

Joining strings together

You can glue strings end to end with the + symbol. This is called concatenation.

first = "Sky"
second = "lark"
word = first + second
print(word)        # Skylark

Here first + second builds a brand-new string by sticking lark onto the end of Sky. Watch out: + does not add a space for you. If you want one, include it yourself:

full = "Ada" + " " + "Lovelace"
print(full)        # Ada Lovelace

You can also repeat a string using *:

print("ho" * 3)    # hohoho
print("-" * 10)    # ----------

"ho" * 3 makes three copies joined together. The second line is a neat trick for drawing a line of ten dashes without typing them all.

Each character has a position

Every character in a string sits at a numbered slot called an index. Counting starts at 0, not 1.

 s  t  a  r
 0  1  2  3

You grab a single character using square brackets:

word = "star"
print(word[0])     # s
print(word[3])     # r

word[0] reaches into the string and pulls out the character at position 0, which is s. You can also count backwards with negative numbers: word[-1] is the last character, r.

Slicing: taking a piece

To pull out a chunk rather than one character, use a slice with a colon: word[start:stop]. Python gives you everything from start up to but not including stop.

word = "rainbow"
print(word[0:4])   # rain
print(word[4:7])   # bow
print(len(word))   # 7
  • word[0:4] takes positions 0, 1, 2 and 3 — the letters rain. Position 4 is left out.
  • word[4:7] takes positions 4, 5 and 6 — bow.
  • len(word) is a built-in that tells you how many characters are in the string: 7.

String methods: tools that come free

Strings come with handy built-in methods you call with a dot. They return a new string — the original never changes.

shout = "quiet please"
print(shout.upper())        # QUIET PLEASE
print(shout.title())        # Quiet Please
print(shout.replace("quiet", "loud"))   # loud please
print("  trim me  ".strip())            # trim me
  • .upper() makes a new string in CAPITALS.
  • .title() capitalises the first letter of each word.
  • .replace("quiet", "loud") swaps every quiet for loud.
  • .strip() removes spaces from the start and end — useful for cleaning up typed input.

Dropping variables into text with f-strings

The neatest way to build a message that includes a variable is an f-string. Put the letter f before the opening quote, then write variables inside {curly braces}.

name = "Maya"
age = 11
print(f"Hi {name}, you are {age} years old.")

Python swaps {name} for Maya and {age} for 11, printing Hi Maya, you are 11 years old. This is far tidier than gluing pieces together with +, and you don't have to worry about turning numbers into text.

Worked example: a friendly greeting machine

Let's combine these ideas into one small program.

name = input("What is your name? ")
clean = name.strip().title()
length = len(clean)

print(f"Welcome, {clean}!")
print(f"Your name has {length} letters.")
print(f"It starts with {clean[0]} and ends with {clean[-1]}.")
print("=" * 20)

Step by step:

  1. input() asks the user to type their name and stores the text.
  2. .strip().title() tidies it: removes stray spaces, then capitalises it nicely. The methods chain left to right.
  3. len(clean) counts the letters.
  4. The f-strings build personalised messages, using clean[0] for the first letter and clean[-1] for the last.
  5. "=" * 20 prints a tidy underline.

If you type ada , it greets Ada with 3 letters, starting with A, ending with a.

Try it yourself

Write a "secret code" program:

  • Ask the user for a word.
  • Print it in UPPERCASE.
  • Print it backwards (hint: slicing with word[::-1] reverses a string).
  • Print how many characters it has.
  • Replace every letter a with a star * and print the result.

Once that works, see if you can join short pieces of text into a poem. When you're ready for the next step, the lesson on lists and arrays shows how to store many strings together.

Quick quiz

Test yourself and earn XP

Which of these is a string?

What does `"ha" * 3` produce?

What is the index of the letter 'c' in `"cat"`?

What does `"Hello".upper()` return?

What prints? ``` name = "Sam" print(f"Hi {name}!") ```

FAQ

Both work the same in Python. Use 'single' or "double" quotes, just keep them matched. Double quotes are handy when your text contains an apostrophe, like "it's sunny", because the apostrophe won't end the string early.

Many programming languages number positions from 0 because the index really means 'how far from the start'. The first character is 0 steps from the start, so it sits at index 0. It feels odd at first, but you get used to it quickly.