Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 134 - 2620_Birla Open Mind C-8
P. 134

    You will get the following output:
                       Output

                    I love programming in
                     Python

                  Traversing a String

                  Traversing means visiting each element of the string and processing it as required by the program. We
                  can access the characters of a string one at a time using indexing.

                  There are two ways of indexing a string:

                      Positive Indexing: Index starts with 0 from left to right.

                      Negative Indexing: Index starts with -1 from right to left. Syntax for traversing a string:

                     Example

                     0    1    2    3    4    5

                    O    R    A    N    G    E

                   -6    -5   -4   -3   -2   -1
                    <name of the string> [index]
                  Program 6: To access different elements of a string

                       Program3.py
                    File  Edit  Format   Run   Options   Window    Help

                    name = 'orange'
                    print(name[0])
                    print(name[-1])

                      Output

                    o
                    e

                  String Operators

                  There are two basic string operators in Python, + and *. Python uses + for concatenation and * for

                  replication:
                     String Concatenation Operator (+): String concatenation operator joins two or more strings into
                     one string.

                      132  Premium Edition-VIII

| 129 130 131 132 133 134 135 136 137 138 139 |