Strings

See w3schools.com for more information and guidance in English.

A string is a sequence of characters, i.e. letters, numbers, symbols, ...

Strings ("string constants") expressed within Python code are surrounded by apostrophies (') or quotation marks ("). If the string is surrounded by apostrophies, it can contain quotation marks and if it is surrounded by quotation marks, it can contain apostopphies.

Example: 'Take it easy', "Elmer's tune" and 'Hamlet said "The time is out of joint"'.

The characters that surround the string (apostrophies or quotation marks) do note belong to the string itself and is not included when the string is printed.

A multi-line string can be defined with the help of three of the surrounding characters. Example: The code

verse = """Dromedaren med sin puckel går i öknen ut på ruckel""" print(verse)
ger utskriften
Dromedaren med sin puckel går i öknen ut på ruckel

Special characters / symbols

Strings can contain unprintable special characters such as "newline", "tabulator", etc. To write such characters, you use the escape character \ (often called backslash) followed by one or several characters. The most important and widely used of these is \n for newline.

Example: print('Hello\nworld!') prints Hello on one line and world on the next line.

To store the escape character in a string, it must be preceded by another escape character. The expression print('\\\n\n\\') writes three lines with a backslash on the first and the last, with a blank line in the middle.

String operators

Code Output Comment
s = "Kilroy" s = s + ' was here'
Concatenation.
print(s) Kilroy was here
print(s[0]) K
print(s[-2]) r Penultimate. Negative index counts in reverse.
print(s[0:6]) Kilroy Substring from (and including) pos 0 to (but not including) pos 6.
print(s[:3]) Kil From the start (pos 0) to (but not including) pos 3.
print(s[-4:-1]) her To the end but not including the last character.
print(s[-4:]) here From position -4 to the end.
print('Ha' + 'ha'*3 + '!') Hahahaha! Repetition and concatentation.
print('was' in s) True

String can also be compared with the relational operators (equals, not equals, inequalities) ==, !=, <, <=, > och >=.

Functions for strings

Funktion Meaning Example
float Reinterprets the string as a floating-point number. Gives an error if that is not possible. float('42') -> 42.0
int Reinterprets the string as an integer. Gives an error if that is not possible. int('42') -> 42
len The length of the string, i.e. the number of characters. len('42') -> 2
list Transforms the sequence of characters in the string into a list. list('42') -> ['4', '2']
ord Gives the character code for a string with a single character. ord('a') -> 97
chr The inverse of ord, giving the string from a character code. ord . ord(97) -> 'a'

Methods for strings

The string data-type (class) has a large number of methods. See the official documentation for a complete listing, and more details. More information.

Note: Since string objects are immutable, methods like replace, upper, etc, new string objects. The original objects remains unchanged.

Method Meaning Example
count(string) Counts the number of (non-overlapping) occurrences of a string inside another string. 'axxxxbxx'.count('x') -> 6
'axxxxbxx'.count('xx') -> 3
'axxxxbxx'.count('xxx') -> 1
find(string) s1.find(s2) returns the index of the first occurrence of s2 in s1, or -1 if s2 does not occur in s1. 'abcd'.find('cd') -> 2
'abcd'.find('cde') -> -1
format(v1, v2, ...) Format conversion. See Formatting. '{:.2f}'.format(3.1) -> '3.10'
index(string) Like find but gives an error if the sought string does not occur in the string being searched.
isalpha() True if only letters. 'åäöü'.isalpha() -> True
isdigit() True if only numerals. '123'.isdigit() -> True
'123.'.isdigit() -> False
join(string) Joins the strings into a single string. The parameter may be a string or a list. See the exemple. '-'.join('abc') -> 'a-b-c'
'**'.join('234') -> '2**3**4'
lower() Gives a new string where all upper-case letters have been exchanged for corresponding lower-case letters. 'Ab+Åd2'.lower() -> 'ab+åd2'
lstrip rstrip strip Removes white space at the start or the end of the string, or both at the start and end ' hej '.lstrip() -> 'hej ' ' hej '.rstrip() -> ' hej' ' hej '.strip() -> 'hej'
partition(delim) Returns a tuple of strings, partitioning it by a given delimiter. See the example. 'name@address'.partition('@') ->
('name', '@', 'address')
replace(s1, s2) Exchanges all occurrences of s1 with s2. 'Hej Name! Name is a nice name.'.replace('Name','Johan') ->
'Meråker'
split() split(delim) Makes a list of the parts of the string. If an argument is provided, it is used as a delimiter, otherwise all "white space" is used to split the string. 'take it easy'.split() ->
['take', 'it', 'easy']
'take it easy'.split('t') ->
['', 'ake i', ' easy']
upper Gives a new string where all lower-case letters have been exchanged for corresponding upper-case letters. 'åäö'.upper() -> 'ÅÄÖ'

Back

Valid CSS!