Python Strings
String is sequence of Unicode characters. We can use single quotes or double quotes to represent strings. Multi-line strings can be denoted using triple quotes, ”’ or “””.
>>> s = ‘This is a string’
>>> s = “This is a string”
>>> s = ”’a multiline
text ”’
>>> s=””” Hello this is multiline
text”””
Like list and tuple, slicing operator [ ] can be used with string. Strings are immutable(cannot be modified).
Example:1
s = 'Hello world!' print(s) print(s[0]) print(s[1]) print("s[4] = ", s[4]) print("s[6:11] = ", s[6:11]) # Generates error # Strings are immutable in Python #s[5] ='d'
Output:
Hello world! H e s[4] = o s[6:11] = world >>>
Python Dictionary
Dictionary is an unordered collection of key-value pairs. It is generally used when we have a huge amount of data. Dictionaries are optimized for retrieving data. We must know the key to retrieve the value.
In Python, dictionaries are defined within braces {} with each item being a pair in the form key:value. Key and value can be of any type.
>>> d = {1:’value’,’key’:2}
>>> type(d)
<class ‘dict’>
We use key to retrieve the respective value. But not the other way around.
example:1:
d = {1:'one',2:'two',3:'three',4:'four',5:'five'} print(type(d)) print(d)
Output:
<class 'dict'> {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'} >>>
Example:2
d = {1:'one',2:'two',3:'three',4:'four',5:'five'} print(type(d)) print(d) print("d[1] = ", d[1]); print("d[2] = ", d[2]); print("d[3] = ", d[3]); print("d[4] = ", d[4]); print("d[5] = ", d[5]);
Output:
<class 'dict'> {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'} d[1] = one d[2] = two d[3] = three d[4] = four d[5] = five >>>