← Learning Hub
Beginner

Strings

A string is text inside quotes. You can use single '...' or double "..." quotes.

Strings are everywhere: names, addresses, messages, product titles, passwords, coupon codes. A big part of real programming is working with text - cleaning it, searching it, joining it, and showing it nicely to users. Python makes this easy.

Single and double quotes do the same job. Pick one style and stay with it. If your text has an apostrophe, use double quotes around it: "Riya's order".

f-strings: the easy way to mix text and values

Example
You can edit this code.

Before f-strings, people joined text with + and had to convert every number with str(). An f-string (the f before the quote) lets you put any variable or even a calculation inside { }, and Python fills in the value. It's shorter, easier to read, and it's what modern Python code uses.

Useful string methods

Example
You can edit this code.

A method is a function that belongs to a value, written with a dot: name.upper(). Strings come with dozens of useful methods. In real apps, strip() is used a lot because users often type extra spaces, and lower() helps when comparing text without worrying about capital letters ("DELHI" vs "delhi").

Indexing and slicing

Each character has a position (an index) starting at 0. A slice takes a part: [start:end], where the end is not included.

Why start at 0? The index means "how many steps from the start". The first character is 0 steps away. Negative indexes count from the end, so -1 is always the last character, no matter how long the text is - very handy.

Example
You can edit this code.
Strings cannot be changed in place. Methods like upper() return a new string.
Key points
  • Strings are text in quotes; use f-strings to mix text and values.
  • Methods like strip(), upper() and replace() return new strings.
  • Indexes start at 0; -1 is the last character; slices [start:end] don't include the end.

📝 Test yourself

1. What is the index of the first character in a string?
2. What does "sale".upper() return?
3. Fill in the function that counts the characters in a string:
("hello")