A string is an ordered sequence of Unicode characters. Create one with single or double quotes.
first = 'Python'
second = "ILoveCompiler"
empty = ""Use the same quote type on both ends. If the text contains an apostrophe, double quotes are convenient: "It's Python".
Triple-quoted strings#
Triple quotes keep line breaks:
message = """Dear learner,
Welcome to ILoveCompiler.
"""
print(message)They are often used for docstrings and multi-line text.
Indexing#
Positions start at zero. Negative indices count from the end.
word = "Python"
print(word[0]) # P
print(word[1]) # y
print(word[-1]) # n
print(word[-2]) # oIndexing outside the string raises IndexError. Test the length first when the position is calculated:
print(len(word)) # 6Slicing#
A slice takes a section with [start:stop:step]. The start is included and the stop is excluded.
word = "programming"
print(word[0:7]) # program
print(word[3:]) # gramming
print(word[:4]) # prog
print(word[::2]) # pormig
print(word[::-1]) # gnimmargorpOmitting start begins at the start. Omitting stop continues to the end. A negative step walks backwards.
Immutability#
Strings cannot be changed in place:
word = "Python"
# word[0] = "J" # TypeErrorBuild a new string instead:
word = "J" + word[1:]
print(word)Jython
Every string method returns a new string.
Escape sequences#
Backslash introduces special characters:
| Escape | Meaning |
| --- | --- |
| \n | New line |
| \t | Tab |
| \\ | Backslash |
| \' | Single quote |
| \" | Double quote |
print("First line\nSecond line")
print("Name:\tAda")Prefix a string with r to treat backslashes literally, which is handy for Windows paths and regular expressions:
print(r"C:\Users\ada")Checking string contents#
text = "Python 3.14"
print("Python" in text) # True
print(text.startswith("Py")) # True
print(text.endswith("14")) # True
print(text.isalpha()) # False: contains a space and digitsThe in operator performs a case-sensitive membership test.
Practice#
Given sentence = "Learning Python is fun", print the first word, the last word, the sentence reversed, and the number of characters. Then replace fun with powerful using a string method and print the new sentence.
