forked from artofproblemsolving/pythonbook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrings.html
More file actions
executable file
·1651 lines (1349 loc) · 74.4 KB
/
strings.html
File metadata and controls
executable file
·1651 lines (1349 loc) · 74.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>7. Strings — How to Think Like a Computer Scientist: Learning with Python 3 (AoPS Edition)</title>
<link rel="stylesheet" href="_static/style.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="_static/codemirrorEdited.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '1.0',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript" src="_static/pywindowCodemirrorC.js"></script>
<script type="text/javascript" src="_static/skulpt.min.js"></script>
<script type="text/javascript" src="_static/skulpt-stdlib.js"></script>
<script type="text/javascript" src="_static/aopsmods.js"></script>
<link rel="copyright" title="Copyright" href="copyright.html" />
<link rel="top" title="How to Think Like a Computer Scientist: Learning with Python 3 (AoPS Edition)" href="index.html" />
<link rel="next" title="8. Lists and Tuples" href="liststuples.html" />
<link rel="prev" title="6. Flow of Control" href="iteration.html" />
</head>
<body>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="liststuples.html" title="8. Lists and Tuples"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="iteration.html" title="6. Flow of Control"
accesskey="P">previous</a> |</li>
<li><a href="index.html">How to Think Like a Computer Scientist: Learning with Python 3 (AoPS Edition)</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="body">
<div class="line-block">
<div class="line"><br /></div>
</div>
<div class="section" id="strings">
<h1>7. Strings<a class="headerlink" href="#strings" title="Permalink to this headline">¶</a></h1>
<div class="section" id="a-compound-data-type">
<span id="index-0"></span><h2>7.1. A compound data type<a class="headerlink" href="#a-compound-data-type" title="Permalink to this headline">¶</a></h2>
<p>So far we have seen built-in types like <tt class="docutils literal"><span class="pre">int</span></tt>, <tt class="docutils literal"><span class="pre">float</span></tt>,
<tt class="docutils literal"><span class="pre">bool</span></tt>, <tt class="docutils literal"><span class="pre">str</span></tt>, and we’ve also seen lists.
Strings and lists are different from the others because they
are made up of smaller pieces. In the case of strings, they’re made up of smaller
strings each containing one <strong>character</strong>.</p>
<p>Types that comprise smaller pieces are called <strong>compound data types</strong>.
Depending on what we are doing, we may want to treat a compound data type as a
single thing, or we may want to access its parts.</p>
</div>
<div class="section" id="working-with-strings-as-single-things">
<h2>7.2. Working with strings as single things<a class="headerlink" href="#working-with-strings-as-single-things" title="Permalink to this headline">¶</a></h2>
<p>We previously saw that each turtle instance has its own attributes and
a number of methods that can be applied to the instance. For example,
we could set the turtle’s color, and we wrote <tt class="docutils literal"><span class="pre">tess.turn(90)</span></tt>.</p>
<p>Just like a turtle, a string is also an object. So each string instance
has its own attributes and methods.</p>
<p>For example:</p>
<div id="stringfirstexample" class="pywindow" >
<div id="stringfirstexample_code_div" style="display: block">
<textarea rows="3" id="stringfirstexample_code" class="active_code" prefixcode="undefined">
ss = "Hello, World!"
tt = ss.upper()
print(tt)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['stringfirstexample_code'] = true;
pythonTool.readOnlyFlags['stringfirstexample_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="stringfirstexample_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="stringfirstexample_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="stringfirstexample_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='stringfirstexample_error'></div>
<div style="text-align: center">
<canvas id="stringfirstexample_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="stringfirstexample_suffix" style="display:none">
</pre>
<pre id="stringfirstexample_pre" class="active_out">
</pre>
<div id="stringfirstexample_files" class="ac-files ac-files-hidden"></div>
</div>
<p><tt class="docutils literal"><span class="pre">upper</span></tt> is a method that can be invoked on any string object
to create a new string, in which all the
characters are in uppercase. (The original string <tt class="docutils literal"><span class="pre">ss</span></tt> remains unchanged.)</p>
<p>There are also methods such as <tt class="docutils literal"><span class="pre">lower</span></tt>, <tt class="docutils literal"><span class="pre">capitalize</span></tt>, and
<tt class="docutils literal"><span class="pre">swapcase</span></tt> that do other interesting stuff.</p>
<p>To learn what methods are available, you can consult the Help documentation: type <tt class="docutils literal"><span class="pre">help(str)</span></tt> at the IDLE shell prompt.</p>
</div>
<div class="section" id="working-with-the-parts-of-a-string">
<h2>7.3. Working with the parts of a string<a class="headerlink" href="#working-with-the-parts-of-a-string" title="Permalink to this headline">¶</a></h2>
<p>The <strong>indexing operator</strong> selects a single character substring from a string. We enclose the <strong>index</strong> of the character that we want in square brackets:</p>
<div id="stringchar1extract" class="pywindow" >
<div id="stringchar1extract_code_div" style="display: block">
<textarea rows="3" id="stringchar1extract_code" class="active_code" prefixcode="undefined">
fruit = "banana"
m = fruit[1]
print(m)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['stringchar1extract_code'] = true;
pythonTool.readOnlyFlags['stringchar1extract_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="stringchar1extract_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="stringchar1extract_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="stringchar1extract_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='stringchar1extract_error'></div>
<div style="text-align: center">
<canvas id="stringchar1extract_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="stringchar1extract_suffix" style="display:none">
</pre>
<pre id="stringchar1extract_pre" class="active_out">
</pre>
<div id="stringchar1extract_files" class="ac-files ac-files-hidden"></div>
</div>
<p>The expression <tt class="docutils literal"><span class="pre">fruit[1]</span></tt> selects character number 1 from <tt class="docutils literal"><span class="pre">fruit</span></tt>, and creates a new
string containing just this one character. The variable <tt class="docutils literal"><span class="pre">m</span></tt> refers to the result.</p>
<p>But remember: computer scientists always start counting
from zero! The letter at subscript position zero of <tt class="docutils literal"><span class="pre">"banana"</span></tt> is <tt class="docutils literal"><span class="pre">b</span></tt>. So at
position <tt class="docutils literal"><span class="pre">[1]</span></tt> we have the letter <tt class="docutils literal"><span class="pre">a</span></tt>.</p>
<p>If we want to access the zero-eth letter of a string, we just place 0,
or any expression that evaluates to 0, inbetween the brackets:</p>
<div id="stringchar0extract" class="pywindow" >
<div id="stringchar0extract_code_div" style="display: block">
<textarea rows="3" id="stringchar0extract_code" class="active_code" prefixcode="undefined">
fruit = "banana"
m = fruit[0]
print(m)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['stringchar0extract_code'] = true;
pythonTool.readOnlyFlags['stringchar0extract_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="stringchar0extract_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="stringchar0extract_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="stringchar0extract_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='stringchar0extract_error'></div>
<div style="text-align: center">
<canvas id="stringchar0extract_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="stringchar0extract_suffix" style="display:none">
</pre>
<pre id="stringchar0extract_pre" class="active_out">
</pre>
<div id="stringchar0extract_files" class="ac-files ac-files-hidden"></div>
</div>
<p>The expression in brackets is called an <strong>index</strong>. An index specifies a member
of an ordered collection, in this case the collection of characters in the string. The index
<em>indicates</em> which one you want, hence the name. It can be any integer
expression.</p>
<p>We can use <tt class="docutils literal"><span class="pre">enumerate</span></tt> to visualize the indices:</p>
<div id="stringcharallextract" class="pywindow" >
<div id="stringcharallextract_code_div" style="display: block">
<textarea rows="2" id="stringcharallextract_code" class="active_code" prefixcode="undefined">
fruit = "banana"
print(list(enumerate(fruit)))</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['stringcharallextract_code'] = true;
pythonTool.readOnlyFlags['stringcharallextract_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="stringcharallextract_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="stringcharallextract_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="stringcharallextract_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='stringcharallextract_error'></div>
<div style="text-align: center">
<canvas id="stringcharallextract_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="stringcharallextract_suffix" style="display:none">
</pre>
<pre id="stringcharallextract_pre" class="active_out">
</pre>
<div id="stringcharallextract_files" class="ac-files ac-files-hidden"></div>
</div>
<p>Do not worry about <tt class="docutils literal"><span class="pre">enumerate</span></tt> at this point, we will see more of it
in the chapter on lists.</p>
<p>Note that indexing returns a <em>string</em> — Python has no special type for a single character.
It is just a string of length 1.</p>
<p>We’ve also seen lists previously. The same indexing notation works to extract elements from
a list:</p>
<div id="listextractexamples" class="pywindow" >
<div id="listextractexamples_code_div" style="display: block">
<textarea rows="4" id="listextractexamples_code" class="active_code" prefixcode="undefined">
prime_nums = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
print(prime_nums[4]) # should print 11
friends = ["Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]
print(friends[3]) # should print Angelina</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['listextractexamples_code'] = true;
pythonTool.readOnlyFlags['listextractexamples_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="listextractexamples_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="listextractexamples_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="listextractexamples_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='listextractexamples_error'></div>
<div style="text-align: center">
<canvas id="listextractexamples_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="listextractexamples_suffix" style="display:none">
</pre>
<pre id="listextractexamples_pre" class="active_out">
</pre>
<div id="listextractexamples_files" class="ac-files ac-files-hidden"></div>
</div>
</div>
<div class="section" id="length">
<span id="index-1"></span><h2>7.4. Length<a class="headerlink" href="#length" title="Permalink to this headline">¶</a></h2>
<p>The <tt class="docutils literal"><span class="pre">len</span></tt> function, when applied to a string, returns the number of characters in a string:</p>
<div id="lengthex1" class="pywindow" >
<div id="lengthex1_code_div" style="display: block">
<textarea rows="2" id="lengthex1_code" class="active_code" prefixcode="undefined">
fruit = "banana"
print(len(fruit))</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['lengthex1_code'] = true;
pythonTool.readOnlyFlags['lengthex1_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="lengthex1_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="lengthex1_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="lengthex1_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='lengthex1_error'></div>
<div style="text-align: center">
<canvas id="lengthex1_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="lengthex1_suffix" style="display:none">
</pre>
<pre id="lengthex1_pre" class="active_out">
</pre>
<div id="lengthex1_files" class="ac-files ac-files-hidden"></div>
</div>
<p>To get the last letter of a string, you might be tempted to try something like
this:</p>
<div id="lastcharexbad" class="pywindow" >
<div id="lastcharexbad_code_div" style="display: block">
<textarea rows="3" id="lastcharexbad_code" class="active_code" prefixcode="undefined">
fruit = "banana"
sz = len(fruit)
print(fruit[sz]) # will generate error</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['lastcharexbad_code'] = true;
pythonTool.readOnlyFlags['lastcharexbad_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="lastcharexbad_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="lastcharexbad_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="lastcharexbad_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='lastcharexbad_error'></div>
<div style="text-align: center">
<canvas id="lastcharexbad_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="lastcharexbad_suffix" style="display:none">
</pre>
<pre id="lastcharexbad_pre" class="active_out">
</pre>
<div id="lastcharexbad_files" class="ac-files ac-files-hidden"></div>
</div>
<p>That won’t work. It causes the runtime error
<tt class="docutils literal"><span class="pre">IndexError:</span> <span class="pre">string</span> <span class="pre">index</span> <span class="pre">out</span> <span class="pre">of</span> <span class="pre">range</span></tt>. The reason is that there is no
character at index position 6 in <tt class="docutils literal"><span class="pre">"banana"</span></tt>.
Because we start counting at zero, the six indexes are
numbered 0 to 5. To get the last character, we have to subtract 1 from
the length of <tt class="docutils literal"><span class="pre">fruit</span></tt>:</p>
<div id="lastcharexgood" class="pywindow" >
<div id="lastcharexgood_code_div" style="display: block">
<textarea rows="3" id="lastcharexgood_code" class="active_code" prefixcode="undefined">
fruit = "banana"
sz = len(fruit)
print(fruit[sz-1]) # will print last character of fruit</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['lastcharexgood_code'] = true;
pythonTool.readOnlyFlags['lastcharexgood_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="lastcharexgood_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="lastcharexgood_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="lastcharexgood_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='lastcharexgood_error'></div>
<div style="text-align: center">
<canvas id="lastcharexgood_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="lastcharexgood_suffix" style="display:none">
</pre>
<pre id="lastcharexgood_pre" class="active_out">
</pre>
<div id="lastcharexgood_files" class="ac-files ac-files-hidden"></div>
</div>
<p>Alternatively, we can use <strong>negative indices</strong>, which count backward from the
end of the string. The expression <tt class="docutils literal"><span class="pre">fruit[-1]</span></tt> yields the last letter,
<tt class="docutils literal"><span class="pre">fruit[-2]</span></tt> yields the second to last, and so on.</p>
<div id="lastcharexbetter" class="pywindow" >
<div id="lastcharexbetter_code_div" style="display: block">
<textarea rows="2" id="lastcharexbetter_code" class="active_code" prefixcode="undefined">
fruit = "banana"
print(fruit[-1]) # will print last character of fruit</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['lastcharexbetter_code'] = true;
pythonTool.readOnlyFlags['lastcharexbetter_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="lastcharexbetter_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="lastcharexbetter_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="lastcharexbetter_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='lastcharexbetter_error'></div>
<div style="text-align: center">
<canvas id="lastcharexbetter_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="lastcharexbetter_suffix" style="display:none">
</pre>
<pre id="lastcharexbetter_pre" class="active_out">
</pre>
<div id="lastcharexbetter_files" class="ac-files ac-files-hidden"></div>
</div>
<p>As you might have guessed, indexing with a negative index also works like this for lists.</p>
<span class="target" id="index-2"></span></div>
<div class="section" id="traversal-and-the-for-loop">
<span id="index-3"></span><h2>7.5. Traversal and the <tt class="docutils literal"><span class="pre">for</span></tt> loop<a class="headerlink" href="#traversal-and-the-for-loop" title="Permalink to this headline">¶</a></h2>
<p>A lot of computations involve processing a string one character at a time.
Often they start at the beginning, select each character in turn, do something
to it, and continue until the end. This pattern of processing is called a
<strong>traversal</strong>. One way to encode a traversal is with a <tt class="docutils literal"><span class="pre">while</span></tt> statement:</p>
<div id="stringtraversallong" class="pywindow" >
<div id="stringtraversallong_code_div" style="display: block">
<textarea rows="6" id="stringtraversallong_code" class="active_code" prefixcode="undefined">
fruit = "banana"
ix = 0
while ix < len(fruit):
letter = fruit[ix]
print(letter)
ix += 1</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['stringtraversallong_code'] = true;
pythonTool.readOnlyFlags['stringtraversallong_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="stringtraversallong_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="stringtraversallong_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="stringtraversallong_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='stringtraversallong_error'></div>
<div style="text-align: center">
<canvas id="stringtraversallong_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="stringtraversallong_suffix" style="display:none">
</pre>
<pre id="stringtraversallong_pre" class="active_out">
</pre>
<div id="stringtraversallong_files" class="ac-files ac-files-hidden"></div>
</div>
<p>This loop traverses the string and displays each letter on a line by itself.
The loop condition is <tt class="docutils literal"><span class="pre">ix</span> <span class="pre"><</span> <span class="pre">len(fruit)</span></tt>, so when <tt class="docutils literal"><span class="pre">ix</span></tt> is equal to the
length of the string, the condition is false, and the body of the loop is not
executed. The last character accessed is the one with the index
<tt class="docutils literal"><span class="pre">len(fruit)-1</span></tt>, which is the last character in the string.</p>
<p>But we’ve previously seen how the <tt class="docutils literal"><span class="pre">for</span></tt> loop can easily iterate over
the elements in a list, and it can do so for strings as well:</p>
<div id="stringtraversalquick" class="pywindow" >
<div id="stringtraversalquick_code_div" style="display: block">
<textarea rows="3" id="stringtraversalquick_code" class="active_code" prefixcode="undefined">
fruit = "banana"
for letter in fruit:
print(letter)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['stringtraversalquick_code'] = true;
pythonTool.readOnlyFlags['stringtraversalquick_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="stringtraversalquick_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="stringtraversalquick_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="stringtraversalquick_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='stringtraversalquick_error'></div>
<div style="text-align: center">
<canvas id="stringtraversalquick_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="stringtraversalquick_suffix" style="display:none">
</pre>
<pre id="stringtraversalquick_pre" class="active_out">
</pre>
<div id="stringtraversalquick_files" class="ac-files ac-files-hidden"></div>
</div>
<p>Each time through the loop, the next character in the string is assigned to the
variable <tt class="docutils literal"><span class="pre">letter</span></tt>. The loop continues until no characters are left. Here we
can see the expressive power the <tt class="docutils literal"><span class="pre">for</span></tt> loop gives us compared to the
while loop when traversing a string.</p>
<p>The following example shows how to use concatenation and a <tt class="docutils literal"><span class="pre">for</span></tt> loop to
generate an abecedarian series. Abecedarian refers to a series or list in which
the elements appear in alphabetical order. For example, in Robert McCloskey’s
book <em>Make Way for Ducklings</em>, the names of the ducklings are Jack, Kack, Lack,
Mack, Nack, Ouack, Pack, and Quack. This loop outputs these names (well, mostly) in order:</p>
<div id="ducklings" class="pywindow" >
<div id="ducklings_code_div" style="display: block">
<textarea rows="4" id="ducklings_code" class="active_code" prefixcode="undefined">
prefixes = "JKLMNOPQ"
suffix = "ack"
for p in prefixes:
print(p + suffix)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['ducklings_code'] = true;
pythonTool.readOnlyFlags['ducklings_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="ducklings_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="ducklings_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="ducklings_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='ducklings_error'></div>
<div style="text-align: center">
<canvas id="ducklings_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="ducklings_suffix" style="display:none">
</pre>
<pre id="ducklings_pre" class="active_out">
</pre>
<div id="ducklings_files" class="ac-files ac-files-hidden"></div>
</div>
<p>It doesn’t quick work, because Ouack and Quack need an extra “u”. We can fix it with an <tt class="docutils literal"><span class="pre">if</span></tt>-<tt class="docutils literal"><span class="pre">else</span></tt> statement:</p>
<div id="ducklingsfixed" class="pywindow" >
<div id="ducklingsfixed_code_div" style="display: block">
<textarea rows="7" id="ducklingsfixed_code" class="active_code" prefixcode="undefined">
prefixes = "JKLMNOPQ"
suffix = "ack"
for p in prefixes:
if p == "O" or p == "Q":
print(p + "u" + suffix)
else:
print(p + suffix)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['ducklingsfixed_code'] = true;
pythonTool.readOnlyFlags['ducklingsfixed_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="ducklingsfixed_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="ducklingsfixed_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="ducklingsfixed_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='ducklingsfixed_error'></div>
<div style="text-align: center">
<canvas id="ducklingsfixed_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="ducklingsfixed_suffix" style="display:none">
</pre>
<pre id="ducklingsfixed_pre" class="active_out">
</pre>
<div id="ducklingsfixed_files" class="ac-files ac-files-hidden"></div>
</div>
</div>
<div class="section" id="slices">
<span id="index-4"></span><h2>7.6. Slices<a class="headerlink" href="#slices" title="Permalink to this headline">¶</a></h2>
<p>A <em>substring</em> of a string is obtained by taking a <strong>slice</strong>. Similarly, we can
slice a list to refer to some sublist of the items in the list:</p>
<div id="slicefirstexample" class="pywindow" >
<div id="slicefirstexample_code_div" style="display: block">
<textarea rows="6" id="slicefirstexample_code" class="active_code" prefixcode="undefined">
s = "Pirates of the Caribbean"
print(s[0:7])
print(s[11:14])
print(s[15:24])
friends = ["Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]
print(friends[2:4])</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['slicefirstexample_code'] = true;
pythonTool.readOnlyFlags['slicefirstexample_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="slicefirstexample_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="slicefirstexample_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="slicefirstexample_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='slicefirstexample_error'></div>
<div style="text-align: center">
<canvas id="slicefirstexample_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="slicefirstexample_suffix" style="display:none">
</pre>
<pre id="slicefirstexample_pre" class="active_out">
</pre>
<div id="slicefirstexample_files" class="ac-files ac-files-hidden"></div>
</div>
<p>The operator <tt class="docutils literal"><span class="pre">[n:m]</span></tt> returns the part of the string from the n’th character
to the m’th character, including the first but excluding the last. This
behavior makes sense if you imagine the indices
pointing <em>between</em> the characters, as in the following diagram:</p>
<blockquote>
<div><img alt="'banana' string" src="_images/banana.png" />
</div></blockquote>
<p>If you imagine this as a piece of paper, the slice operator <tt class="docutils literal"><span class="pre">[n:m]</span></tt> copies out
the part of the paper between the <tt class="docutils literal"><span class="pre">n</span></tt> and <tt class="docutils literal"><span class="pre">m</span></tt> positions. Provided <tt class="docutils literal"><span class="pre">m</span></tt> and <tt class="docutils literal"><span class="pre">n</span></tt> are
both within the bounds of the string, your result will be of length (m-n).</p>
<p>Three tricks are added to this: if you omit the first index (before the colon),
the slice starts at the beginning of the string (or list). If you omit the second index,
the slice extends to the end of the string (or list). Similarly, if you provide value for
<tt class="docutils literal"><span class="pre">n</span></tt> that is bigger than the length of the string (or list), the slice will take all the
values up to the end. (It won’t give an “out of range” error like the normal indexing operation
does.) Thus:</p>
<div id="slicesecondexample" class="pywindow" >
<div id="slicesecondexample_code_div" style="display: block">
<textarea rows="4" id="slicesecondexample_code" class="active_code" prefixcode="undefined">
fruit = "banana"
print(fruit[:3])
print(fruit[3:])
print(fruit[3:999])</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['slicesecondexample_code'] = true;
pythonTool.readOnlyFlags['slicesecondexample_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="slicesecondexample_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="slicesecondexample_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="slicesecondexample_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='slicesecondexample_error'></div>
<div style="text-align: center">
<canvas id="slicesecondexample_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="slicesecondexample_suffix" style="display:none">
</pre>
<pre id="slicesecondexample_pre" class="active_out">
</pre>
<div id="slicesecondexample_files" class="ac-files ac-files-hidden"></div>
</div>
<p>What do you think <tt class="docutils literal"><span class="pre">s[:]</span></tt> means? What about <tt class="docutils literal"><span class="pre">friends[4:]</span></tt>? (Try it in the above examples and see!)</p>
</div>
<div class="section" id="string-comparison">
<span id="index-5"></span><h2>7.7. String comparison<a class="headerlink" href="#string-comparison" title="Permalink to this headline">¶</a></h2>
<p>The comparison operators work on strings. To see if two strings are equal:</p>
<div id="stringcomp1" class="pywindow" >
<div id="stringcomp1_code_div" style="display: block">
<textarea rows="3" id="stringcomp1_code" class="active_code" prefixcode="undefined">
word = "banana"
if word == "banana":
print("Yes, we have no bananas!")</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['stringcomp1_code'] = true;
pythonTool.readOnlyFlags['stringcomp1_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="stringcomp1_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="stringcomp1_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="stringcomp1_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='stringcomp1_error'></div>
<div style="text-align: center">
<canvas id="stringcomp1_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="stringcomp1_suffix" style="display:none">
</pre>
<pre id="stringcomp1_pre" class="active_out">
</pre>
<div id="stringcomp1_files" class="ac-files ac-files-hidden"></div>
</div>
<p>Other comparison operations are useful for putting words in
<em>lexicographical</em> order:</p>
<div id="stringcomplex" class="pywindow" >
<div id="stringcomplex_code_div" style="display: block">
<textarea rows="7" id="stringcomplex_code" class="active_code" prefixcode="undefined">
word = "apple"
if word < "banana":
print("Your word, " + word + ", comes before banana.")
elif word > "banana":
print("Your word, " + word + ", comes after banana.")
else:
print("Yes, we have no bananas!")</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['stringcomplex_code'] = true;
pythonTool.readOnlyFlags['stringcomplex_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="stringcomplex_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="stringcomplex_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="stringcomplex_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='stringcomplex_error'></div>
<div style="text-align: center">
<canvas id="stringcomplex_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="stringcomplex_suffix" style="display:none">
</pre>
<pre id="stringcomplex_pre" class="active_out">
</pre>
<div id="stringcomplex_files" class="ac-files ac-files-hidden"></div>
</div>
<p>This is similar to the alphabetical order you would use with a dictionary,
except that all the uppercase letters come before all the lowercase letters. Try changing <tt class="docutils literal"><span class="pre">word</span></tt> to “Zebra” (with a capital “Z”) in the above code, and see what happens.</p>
<p>A common way to address this problem is to convert strings to a standard
format, such as all lowercase, before performing the comparison. A more
difficult problem is making the program realize that zebras are not fruit.</p>
</div>
<div class="section" id="strings-are-immutable">
<span id="index-6"></span><h2>7.8. Strings are immutable<a class="headerlink" href="#strings-are-immutable" title="Permalink to this headline">¶</a></h2>
<p>It is tempting to use the <tt class="docutils literal"><span class="pre">[]</span></tt> operator on the left side of an assignment,
with the intention of changing a character in a string. For example:</p>
<div id="changelettererror" class="pywindow" >
<div id="changelettererror_code_div" style="display: block">
<textarea rows="3" id="changelettererror_code" class="active_code" prefixcode="undefined">
greeting = "Hello, world!"
greeting[0] = 'J' # ERROR!
print(greeting)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['changelettererror_code'] = true;
pythonTool.readOnlyFlags['changelettererror_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="changelettererror_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="changelettererror_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="changelettererror_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='changelettererror_error'></div>
<div style="text-align: center">
<canvas id="changelettererror_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="changelettererror_suffix" style="display:none">
</pre>
<pre id="changelettererror_pre" class="active_out">
</pre>
<div id="changelettererror_files" class="ac-files ac-files-hidden"></div>
</div>
<p>Instead of producing the output <tt class="docutils literal"><span class="pre">Jello,</span> <span class="pre">world!</span></tt>, this code produces the
runtime error <tt class="docutils literal"><span class="pre">TypeError:</span> <span class="pre">'str'</span> <span class="pre">object</span> <span class="pre">does</span> <span class="pre">not</span> <span class="pre">support</span> <span class="pre">item</span> <span class="pre">assignment</span></tt>.</p>
<p>Strings are <strong>immutable</strong>, which means you can’t change an existing string. The
best you can do is create a new string that is a variation on the original:</p>
<div id="changelettercorrect" class="pywindow" >
<div id="changelettercorrect_code_div" style="display: block">
<textarea rows="3" id="changelettercorrect_code" class="active_code" prefixcode="undefined">
greeting = "Hello, world!"
newGreeting = "J" + greeting[1:]
print(newGreeting)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['changelettercorrect_code'] = true;
pythonTool.readOnlyFlags['changelettercorrect_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="changelettercorrect_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="changelettercorrect_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="changelettercorrect_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='changelettercorrect_error'></div>
<div style="text-align: center">
<canvas id="changelettercorrect_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="changelettercorrect_suffix" style="display:none">
</pre>
<pre id="changelettercorrect_pre" class="active_out">
</pre>
<div id="changelettercorrect_files" class="ac-files ac-files-hidden"></div>
</div>
<p>The solution here is to concatenate a new first letter onto a slice of
<tt class="docutils literal"><span class="pre">greeting</span></tt>. This operation has no effect on the original string.</p>
</div>
<div class="section" id="the-in-and-not-in-operators">
<span id="index-7"></span><h2>7.9. The <tt class="docutils literal"><span class="pre">in</span></tt> and <tt class="docutils literal"><span class="pre">not</span> <span class="pre">in</span></tt> operators<a class="headerlink" href="#the-in-and-not-in-operators" title="Permalink to this headline">¶</a></h2>
<p>The <tt class="docutils literal"><span class="pre">in</span></tt> operator tests for membership. When both of the arguments to <tt class="docutils literal"><span class="pre">in</span></tt>
are strings, <tt class="docutils literal"><span class="pre">in</span></tt> checks whether the left argument is a substring of the right
argument.</p>
<div id="stringinexamples" class="pywindow" >
<div id="stringinexamples_code_div" style="display: block">
<textarea rows="8" id="stringinexamples_code" class="active_code" prefixcode="undefined">
>>> "p" in "apple"
True
>>> "i" in "apple"
False
>>> "ap" in "apple"
True
>>> "pa" in "apple"
False</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['stringinexamples_code'] = false;
pythonTool.readOnlyFlags['stringinexamples_code'] = true;
</script>
<div id='stringinexamples_error'></div>
<pre id="stringinexamples_suffix" style="display:none">
</pre>
</div>
<p>Note that a string is a substring of itself, and the empty string is a
substring of any other string. (Also note that computer scientists
like to think about these edge cases quite carefully!)</p>
<div id="stringinmoreexamples" class="pywindow" >
<div id="stringinmoreexamples_code_div" style="display: block">
<textarea rows="8" id="stringinmoreexamples_code" class="active_code" prefixcode="undefined">
>>> "a" in "a"
True
>>> "apple" in "apple"
True
>>> "" in "a"
True
>>> "" in "apple"
True</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['stringinmoreexamples_code'] = false;
pythonTool.readOnlyFlags['stringinmoreexamples_code'] = true;
</script>
<div id='stringinmoreexamples_error'></div>
<pre id="stringinmoreexamples_suffix" style="display:none">
</pre>
</div>
<p>The <tt class="docutils literal"><span class="pre">not</span> <span class="pre">in</span></tt> operator returns the logical opposite results of <tt class="docutils literal"><span class="pre">in</span></tt>:</p>
<div id="stringinonemoreexample" class="pywindow" >
<div id="stringinonemoreexample_code_div" style="display: block">
<textarea rows="2" id="stringinonemoreexample_code" class="active_code" prefixcode="undefined">
>>> "x" not in "apple"
True</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['stringinonemoreexample_code'] = false;
pythonTool.readOnlyFlags['stringinonemoreexample_code'] = true;
</script>
<div id='stringinonemoreexample_error'></div>
<pre id="stringinonemoreexample_suffix" style="display:none">
</pre>
</div>
<p>Combining the <tt class="docutils literal"><span class="pre">in</span></tt> operator with string concatenation using <tt class="docutils literal"><span class="pre">+</span></tt>, we can
write a function that removes all the vowels from a string:</p>
<div id="removevowels" class="pywindow" >
<div id="removevowels_code_div" style="display: block">
<textarea rows="10" id="removevowels_code" class="active_code" prefixcode="undefined">
def remove_vowels(s):
''' returns string with vowels removed from s '''
vowels = "aeiouAEIOU"
sWithoutVowels = ""
for x in s:
if x not in vowels:
sWithoutVowels += x
return sWithoutVowels
print(remove_vowels("compsci")) # should print "cmpsc"</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['removevowels_code'] = true;
pythonTool.readOnlyFlags['removevowels_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="removevowels_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="removevowels_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="removevowels_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='removevowels_error'></div>
<div style="text-align: center">