Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 136 - 2609_Logicode
P. 136

    TRAVERSING A STRING
                      Traversing means visiting each element 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:

                         Positive Indexing: Index from left starts with 0.

                         Negative Indexing: Index from right starts with -1.
                      The syntax for traversing a string is as follows:

                        <name of the string> [index]
                      Program 5: To access different elements of a string

                          Program5.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. The description of these operators are as follows:
                         String Concatenation Operator (+): String concatenation operator joins two or more strings
                        into one.

                      Program 6: To join two or more strings using string concatenation operator

                          Program6.py
                       File  Edit  Format   Run   Options   Window    Help

                       s1 = 'Here'
                       s2 = 'Is'
                       s3 = 'Python'
                       s = s1 + s2 + s3                                             Output
                       print(s)                                                  HereIsPython

                         String Replication Operator (*): The replication operator is used to repeat the string for a
                        given number of times.

                      134   Premium Edition-VIII

| 131 132 133 134 135 136 137 138 139 140 141 |