Strings | Triple-quoted strings, for statement with in, conversion, changing strings

Triple-quoted strings

Triple-quoted strings are useful when you need multiline text in your program, for documentation strings (which are string literals that are taken as comments when they appear at specific points in your file), and as a way to temporarily disable lines of code during development.

>>> string1 = '''This is 
... a three line
... string'''
>>> string1
'This is \na three line\nstring'
>>> print(string1)
This is 
a three line
string

Iterate over strings in loops using for statement with in

>>> for c in myjob:
...     print(c)
... 
d
e
v
e
l
o
p
e
r
>>> 'i' in myjob
False
>>> 'v' in myjob
True

Conversion

You can’t mix strings and number types around operators such as +, but you can manually convert operands before that operation if needed.

>>> str1 = '23'
>>> int1 = 15
>>> str1 + int1
Traceback (most recent call last):
  File "", line 1, in 
TypeError: Can't convert 'int' object to str implicitly
>>> int(str1) + int1
38
>>> str1 + str(int1)
'2315'

Character code conversions to its underlying integer code.

>>> ord('d')
100
>>> chr(100)
'd'

Changing strings

If you want to change a string you have to make a new one.

>>> name = 'dan '
>>> name = name + 'dumitrache'
>>> name
'dan dumitrache'
>>> name = name[:3] + ' developer'
>>> name
'dan developer'

Replace a few characters with other characters.

>>> name = 'Dan Dumitrache'
>>> name = name.replace('Dumi', 'Mi')
>>> name
'Dan Mitrache'

Leave a Reply