Index, membership, size, slicing and iteration
in
)
and the size function (len()
)Built-in functions (BIFs) are always available
...we again and again avoid doing complicated work and instead find simpler solutions - often relying on library facilities. That's the essence of programming: the continuing search for simplicity.
'text'
, ""
, ''''''
,
""""""
s.lower() -> str
s.split([sep[, maxsplit]]) -> list of strings
s.upper() -> str
...
#!/usr/bin/env python3
a_string = 'What a beautiful snake!'
a_string.upper()
print(a_string)
a_string = a_string.upper()
print(a_string)
print()
print(a_string.split())
a_string = 'Steve, Paul, Susan, Anna, Peter, Amy'
print(a_string.split(', '))
#!/usr/bin/env python3
a_string = "What a beautiful snake!"
char = a_string[0]
char = a_string[1]
char = a_string[-1]
char = a_string[-3]
substring = a_string[1:5]
substring = a_string[1:-3]
substring = a_string[:-2]
substring = a_string[-2:]
result = a_string[::2]
Defined in PEP 498 - Literal String Interpolation
f'text {var} text'
, f""
, f''''''
,
f""""""
#!/usr/bin/env python3
name = 'Pat'
points = 3
print(f'{name} received {points} points.')
value = 3.1473
s = f'The formatted value is {value:.2f}.'
print(s)
Iterate over the elements of a sequence
Each time the body of a for loop runs, a variable is set to the next element of a sequence
#!/usr/bin/env python3
A_STRING = 'What a beautiful snake!'
for char in A_STRING:
print(char)
for index, char in enumerate(A_STRING):
print(f'{index:2}: {char}')
range(.)
range(stop) -> range object
range(start, stop[, step]) -> range object
#!/usr/bin/env python3
total = 0
for i in range(5):
total += i
for _i in range(5):
print("Repeated action")
sum_even = 0
for i in range(10, 0, -2):
sum_even += i
open(.)
read()
, readline()
,
readlines()
or iterate over its contentclose()
or
implicitly (end of with
)The recommended way to read files is
with open(filename, encoding='utf-8') as f:
for line in f:
print(line, end="")
Note that filename
must contain a
the name of a readable file (string)
enumerate(.)
, open(.)
,
range(.)