Create text, pick out characters by position, slice, join and repeat.
# string creation
text = "Hello"
text2 = 'World'
multiline = """This is
a multiline
string"""
Single and double quotes mean the same thing; triple quotes let a string span several lines.
# access characters
text = "Hello"
text[0]
# ans: 'H'
text[-1]
# ans: 'o'
text[1]
# ans: 'e'
Positions count from 0 on the left, or from -1 on the right.
text = "Hello, World!"
text[0:5]
# ans: 'Hello'
text[7:]
# ans: 'World!'
text[:5]
# ans: 'Hello'
[start:stop] includes start and stops before stop. A missing end means "to the edge".
# combine strings
"Hello" + " " + "World"
# ans: "Hello World"
greeting = "Hello"
name = "Alice"
greeting + ", " + name
# ans: "Hello, Alice"
# repeat strings
"Ha" * 3
# ans: "HaHaHa"
"=" * 10
# ans: "=========="
# get the length
len("Hello")
# ans: 5
len("")
# ans: 0
Predict each result, then press → to see which characters are picked.
# negative index?
s = "Python"
s[-1]
# ans: 'n'
s[-2]
# ans: 'o'
# slicing with a step?
s = "abcdefg"
s[::2]
# ans: 'aceg'
The third number is the step: take every 2nd character.
# reverse a string?
s = "Hello"
s[::-1]
# ans: 'olleH'
A step of -1 walks from the right end to the left: the small numbers show the order.
# string immutability?
s = "Hello"
s[0] = 'h'
# ans: TypeError (strings are immutable)
Make a new string instead: s = 'h' + s[1:].
# concatenation vs join?
"a" + "b" + "c"
# ans: "abc"
"".join(["a", "b", "c"])
# ans: "abc"
# membership test?
"ell" in "Hello"
# ans: True
"xyz" in "Hello"
# ans: False
# empty string?
s = ""
len(s)
# ans: 0
bool(s)
# ans: False
# string multiplication?
"0" * 5
# ans: "00000"
# escape characters?
s = "Line1\nLine2"
len(s)
# ans: 11 (\n is one character)
# raw string?
s = r"C:\new\path"
# ans: "C:\\new\\path"
In a raw string a backslash is just a backslash, so \n stays two characters. Python shows each one doubled when it prints the value.
s[0] is the first character, s[-1] the last.
s[a:b] runs from a up to, not including, b; s[::-1] reverses.
You can't change a character in place; build a new string.
+, *, in, lenJoin, repeat, search and measure.