</>CodexBash
Python
PythonBeginner11 min

Strings, formatting and input

Indexing and slicing text, the string methods you will use every day, f-strings for formatting, and reading input with input().

Indexing and slicing a stringstep 1/5
p
0
y
1
t
2
h
3
o
4
n
5
s = pythonlen = 6
Each character has a position, starting at 0. A string of length 6 has positions 0 to 5.

Most programs read text, change it and print it. Python's strings make that pleasant.

Making strings#

Single and double quotes mean the same thing; pick whichever avoids escaping:

a = "It's fine"
b = 'She said "hi"'
c = """Three quotes
let a string span lines"""

\n inside a string is a new line and \t a tab.

Indexing#

Each character has a position, starting at 0. Negative positions count from the end:

word = "python"
word[0]     # 'p'
word[5]     # 'n'
word[-1]    # 'n': the last character
len(word)   # 6

Asking for word[6] is an IndexError: positions run from 0 to len(word) - 1.

Slicing#

s[start:stop] takes the characters from start up to, but not including, stop:

word = "python"
word[0:2]     # 'py'
word[2:]      # 'thon': from 2 to the end
word[:3]      # 'pyt': from the start to 3
word[::-1]    # 'nohtyp': the whole string, backwards

s[::-1] is the quickest palindrome check in any language: s == s[::-1].

Strings cannot be changed#

word = "python"
word[0] = "P"        # TypeError
word = "P" + word[1:]   # build a new string instead: 'Python'

Every string method returns a new string and leaves the original alone.

Methods you will use constantly#

s = "  Hello, World  "
s.strip()            # 'Hello, World'      spaces removed from both ends
s.lower()            # '  hello, world  '
s.upper()            # '  HELLO, WORLD  '
s.replace("l", "L")  # '  HeLLo, WorLd  '
s.find("World")      # 9, or -1 if not found
"World" in s         # True

"a,b,c".split(",")           # ['a', 'b', 'c']
"one two  three".split()     # ['one', 'two', 'three']: any whitespace
"-".join(["a", "b", "c"])    # 'a-b-c'

"abc".isalpha()   # True
"123".isdigit()   # True
"a1".isalnum()    # True

split and join are opposites, and between them they handle most text processing.

Building text: f-strings#

Put an f before the quotes and anything in { } is worked out and inserted:

name = "Asha"
score = 87.456
print(f"{name} scored {score}")          # Asha scored 87.456
print(f"{name} scored {score:.1f}")      # Asha scored 87.5
print(f"{name:>10}|")                    # '      Asha|' right-aligned in 10
print(f"{2 + 3 = }")                     # '2 + 3 = 5', handy for debugging

Avoid building long strings with + in a loop. Each + copies the whole string so far. Collect pieces in a list and "".join(pieces) once at the end.

Reading input#

input() waits for the user to type a line and returns it as a string, always:

name = input("Your name: ")
print(f"Hello, {name}")

Because it is always a string, numbers need converting:

age = int(input("Age: "))

Several numbers on one line are split first:

a, b = map(int, input().split())     # type: 3 4
print(a + b)                         # 7

map(int, ...) applies int to each piece. You will see this line in a lot of competitive programming code.

Key points#

  • Positions start at 0; s[-1] is the last character.
  • Slicing s[a:b] stops before b; s[::-1] reverses.
  • Strings never change; methods return new ones.
  • split breaks text up, join puts it back together.
  • f-strings format values; input() always returns a string.

Next: making decisions with if.

Practise it

The same idea, in the order it is worth meeting it.

  1. Not startedIs it a palindromeEasy
  2. Not startedCancel out neighbouring pairsEasy
Create a free account to track your progress