Unays Learn ยท Python

Working with text in Python: strings and string methods

A huge amount of programming is working with text: names, messages, files, web pages. Python has many built-in tools that make text easy to handle.

Indexing and slicing

word = "Python"
print(word[0])     # P   first character
print(word[-1])    # n   last character
print(word[0:3])   # Pyt characters 0, 1 and 2
print(word[2:])    # thon from index 2 to the end
print(word[::-1])  # nohtyP reversed
print(len(word))   # 6

Positions start at 0. In a slice [start:end], the end position is not included.

Strings cannot be changed in place

String methods return a new string; the original stays the same:

name = "  arta krasniqi  "
clean = name.strip().title()
print(clean)        # Arta Krasniqi
print(repr(name))   # '  arta krasniqi  ' unchanged

Useful string methods

s = "Learning Python is fun"
print(s.upper())                  # LEARNING PYTHON IS FUN
print(s.lower())                  # learning python is fun
print(s.replace("fun", "great"))  # Learning Python is great
print(s.startswith("Learn"))      # True
print(s.find("Python"))           # 9  (index where it starts, -1 if missing)
print("python" in s.lower())      # True
print(s.count("n"))               # 4

split and join

split breaks text into a list; join glues a list back into text:

line = "apple,banana,cherry"
fruits = line.split(",")
print(fruits)               # ['apple', 'banana', 'cherry']
print(" | ".join(fruits))   # apple | banana | cherry

sentence = "the quick brown fox"
print(len(sentence.split()))  # 4 words

With no argument, split() splits on any run of spaces, tabs or new lines.

Formatting with f-strings

name, score, total = "Dren", 17, 20
print(f"{name} scored {score}/{total}")
print(f"That is {score / total:.1%}")   # That is 85.0%
print(f"Price: {4.5:.2f} EUR")          # Price: 4.50 EUR
print(f"|{name:>8}|")                   # |    Dren| right-aligned in 8 spaces

Project: check a password

def password_feedback(pw):
    problems = []
    if len(pw) < 12:
        problems.append("use at least 12 characters")
    if pw.lower() == pw or pw.upper() == pw:
        problems.append("mix upper and lower case letters")
    if not any(ch.isdigit() for ch in pw):
        problems.append("add a number")
    return "Strong enough!" if not problems else "Try to: " + "; ".join(problems)

print(password_feedback("sunshine"))
print(password_feedback("Blue-Mountain-Lake-42"))

Length matters most for password strength: a long passphrase of several random words beats a short password full of symbols.

Try it yourself

In Unays Code, write a program that reads a sentence and prints it with each word capitalised, the number of vowels, and whether it is a palindrome when spaces and capitals are ignored.

This tutorial was written with AI assistance and reviewed by Unays. The runnable code examples were tested before publishing. Spotted a mistake? Tell us at [email protected].