- String Literals
- Escape Sequences:
'\n','\t', etc - Raw Strings
- Ascii Codes:
ordandchr - String Operations
- Concatenation:
a + b,a += b - Multiplication:
a * b,a *= b - Length: len(a)
- Access:
a[i] - Slicing:
a[i:j],a[i:j:k] - Find:
a.find(b) - Converting Case:
a.upper(),a.lower(),a.title() - Starts-with and Ends-with:
startswith,endswith - Replace
a.replace(b, c) - Strip
a.strip() - Split:
a.split(b) - Join:
a.join(b) - Count:
a.count(b)
- Concatenation:
- f-strings
infor char in text:- Docstrings
Strings represent text in Python. Strings in Python are encoded in Unicode, which means their reach extends far beyond ASCII. You can use Chinese characters, Arabic characters, and more.
To define a string literal, you can enclose text in either single-quotes or double-quotes, but you should stay consistent. You can use single-quotes inside a string enclosed in double-quotes and vice-versa.
'this is a string declaration'this is a string declaration
'șʈȓЇиǵʂ ářƏ ūŋĭçóďę abcABC123!@#'șʈȓЇиǵʂ ářƏ ūŋĭçóďę abcABC123!@#
"we can also use double quotes"we can also use double quotes
'using single-quotes "allows" you to use double-quotes inside'using single-quotes "allows" you to use double-quotes inside
"and 'vice versa' with double-quotes"and 'vice versa' with double-quotes
Escape sequences allow us to define special characters within strings.
\'allows you to have a single quote inside a string enclosed in single quotes\"allows you to have a double-quote inside a string enclosed in double-quotes\nrepresents a new-line\trepresents a tab\\represents a backslash\xhhhhrepresents a unicode character with id 'hhhh', e.g.\u0394
'we can use \'single quotes\' in a single-quoted string'we can use 'single quotes' in a single-quoted string
"we can use \"double quotes\" in a double-quoted string"we can use "double quotes" in a double-quoted string
'we can also use a line break\na\ttab\nand a backslash \\\nand this \u0394'we can also use a line break a tab and a backslash
and this Δ
Prefixing a string with 'r' will ignore any escape sequences and interpret the string literally.
r'this is a raw string \n\t\\'this is a raw string \n\t\\
There are two built-in functions for switching back and forth between characters and their ascii codes: chr and ord. You can find more information about these in the official docs for chr and ord. You can view the ASCII table here
print(ord('a')) # 97
print(chr(97))) # aRemember that strings are immutable meaning their values cannot be changed. Each of these operations returns a new string. You can find some reasons why strings are immutable here.
Combine two strings into one
'hello' + ' ' + 'world'hello world
s = 'hello'
s += ' world'
print(s)hello world
Repeat a string
s = 'hello! '
print('hello! ' * 4)hello! hello! hello! hello!
Get the length of a string
s = 'hello world!'
print(len(s))12
Get the character at a given index, indices start at 0.
# 012345
s = 'hello!'
print(s[0]) # h
print(s[4]) # oSlicing allows you to extract a portion of a string. The syntax is string[start_index : end_index : increment].
# 0123456789..
s = 'hello world!'
print(s[3:9]) # lo worIf you leave out the starting index, it's implied to be the start of the string.
# 0123456789..
s = 'hello world!'
print(s[:9]) # hello worIf you leave out the ending index, it's implied to be the end of the string.
# 0123456789..
s = 'hello world!'
print(s[9:]) # ldYou may optionally add a third number, the increment. The code below will yield every other character.
# 0123456789..
s = 'hello world!'
print(s[::2]) # hlowrdYou can use the increment to reverse a string.
# 0123456789..
s = 'hello world!'
print(s[::-1]) # dlrow ollehs.find(a) returns the index of a the first occurance of a
print('hello world'.find('l'))2
s.upper() converts to upper case
print('hello'.upper()) # HELLOs.lower() converts to lower case
print('Hello'.lower()) # hellos.title() makes the first letter of each word a capital
print('hello world'.title()) # Hello Worlda.startswith(b) returns true if a starts with b
print('hello world'.startswith('hello')) # True
print('hello world'.startswith('world')) # Falsea.endswith(b) returns true if the string ends with b
print('hello world'.endswith('hello')) # False
print('hello world'.endswith('world')) # Truea.replace(b, c) replaces occurances of string b with string c
print('hello world'.replace('hello', 'goodbye')) # goodbye worlds.strip()removes leading and trailing characters, if given no parameter, it'll strip whitespace
print(' hello\t\n '.strip())hello
print('__%__hello_world__%__'.strip('_%')) # hello_worlds.split(delimeter) splits a string into a list, if no parameter is given, it'll split on whitespace
fruits = 'apples, bananas, pears'
print(fruits.split(', ')) # ['apples', 'bananas', 'pears']delimeter.join(list) combines the elements of a list into a single string, separated by the delimeter
print(' - '.join(['apples', 'bananas', 'pears']) # apples - bananas - pearsprint('abcacba'.count('a')) # 3We can use f-strings to quickly format text with variables, f-strings are prefixed with an f, and contain curly braces {} to include variables or even expressions.
a = 'one'
b = 2
print(f'a is {a} and b is {b}') # a is one and b is 2
print(f'1+1={1+1}) # 1+1=2if 'h' in 'hello world!':
print('success!')success!
text = 'Hey!'
if char in text:
print(char)H e y !
Docstrings are a special kind of multi-line string that's used for generating documentation. You can read more here