Chapter 05
Chapter 05
Chapter 5
Sequences: Strings, Lists, and Files
H e l l o B o b
0 1 2 3 4 5 6 7 8
>>> greet = "Hello Bob"
>>> greet[0]
'H'
>>> print(greet[0], greet[2], greet[4])
Hlo
>>> x = 8
>>> print(greet[x - 2])
B
0 1 2 3 4 5 6 7 8
• In a string of n characters, the last character is
at position n-1 since we start counting with 0.
• We can index from the right side using negative
indexes.
>>> greet[-1]
'b'
>>> greet[-3]
'B'
Spam!
Operator Meaning
+ Concatenation
* Repetition
<string>[] Indexing
<string>[:] Slicing
len(<string>) Length
for <var> in <string> Iteration through characters
def main():
main()
def main():
main()
def main():
print ("Change Counter\n")
Please enter the count of each coin type. Please enter the count of each coin type.
Quarters: 0 Quarters: 12
Dimes: 0 Dimes: 1
Nickels: 0 Nickels: 0
Pennies: 1 Pennies: 4
The total value of your change is $0.01 The total value of your change is $3.14
Goodbye 32
• When stored in a file:
Hello\nWorld\n\nGoodbye 32\n
def main():
fname = input("Enter filename: ")
infile = open(fname,'r')
data = infile.read()
print(data)
main()
def main():
print ("This program creates a file of usernames from a")
print ("file of names.")