Page 134 - 2622_Delhi Police Public School_C-8
P. 134

Syntax for traversing a string:

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


                   Program6.py                                                 Output
                File  Edit  Format   Run   Options   Window    Help         o

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






              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.


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


                   Program7.py                                                 Output
                File  Edit  Format   Run   Options   Window    Help         HereIsPython

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





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

              Program 8: To repeat a string using string replication operator

                   Program8.py                                                 Output

                File  Edit  Format   Run   Options   Window    Help         HelloHelloHello
                s1 = 'Hello'
                s = s1 * 3
                print(s)











                        Premium Edition-VIII
                132
   129   130   131   132   133   134   135   136   137   138   139