Brainlag
  1. Library
  2. Concepts
  3. Python

Strings and text

Strings hold text. Index and slice them like lists, tidy them with methods, and build messages with f-strings. Methods never change the original.

Python8 min

Text is a sequence

A string is text in quotes. Like a list, it has positions: tag = "NeonFox", then tag[0] is "N", tag[-1] is "x" and tag[:4] is "Neon". len(tag) counts the characters, and "Fox" in tag checks for a piece of text.

An f-string drops values into text: f"{tag} has {hp} HP". Anything inside the curly brackets is worked out first.

Methods give back new strings

A string can never be changed in place. tag.upper() does not alter tag. It makes a new string and hands it back, so you have to catch it with a name:

Python
tag = "  NeonFox  "
tag.strip()           # result thrown away
tag = tag.strip()     # now tag is "NeonFox"

Handy ones: strip() trims spaces at both ends, lower() and upper() change case, replace("a", "b") swaps text, and split() cuts a sentence into a list of words.

Run it: a chat message

Run it, then change one thing and run it again.

main.py to run
message = "  gg EVERYONE, good game  "
clean = message.strip().lower()
words = clean.split()

print(clean)
print(len(words), "words, first is", words[0])
print(f"Shouted: {clean.upper()}!")
print("Polite?", "good game" in clean)

The username that stays messy

New usernames are stored trimmed and in lower case. This should print @neonfox99 but the spaces and capitals are still there. Fix it.

exercise_1.py to run
username = "  NeonFox99 "
username.strip()
username.lower()
print("@" + username)

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.