PYTHON PROGRAMMING. PART II: PYTHON OBJECTS AND DATA STRUCTURE BASICS. UNIT 3: STRING. PART I: BASICS OF STRING

                                     PYTHON PROGRAMMING

 PART II: PYTHON OBJECTS AND DATA STRUCTURE BASICS

UNIT 3: STRING

PART I: BASICS OF STRING

I. Definition

   Strings are used to represent and manipulate a sequence of characters.

    Example: "Khiem", "Hello World", "Yesterday, all my trouble seems so far away".

II. String basics

  1. String indexing and slicing

      a) String indexing

          We know that strings are sequences of characters so we can use indexes to call parts of the string!

             Let s = "John"

             We have: s[0] = "J"

                            s[2] = "h"

                            s[-1] = "n" (-1 is defined as the last character in the string)

              We can also use negative numbers on indexing, as the above example.

        b) String slicing:

           We use the colon : to slice the string, which grabs everything up to a designated point.

                print(s[1:])     # Grab everything past the first term all the way to the length of s which is len(s)                       => "ohn"

                print(s)          #Notice that s has no changes.

                     =>  "John"

                print(s[:3])    #Grab everything up to the 3rd index, but notably, it does not include the 3rd index.

                     => "Joh"

                print(s[:])    #Grab everything!

                     => "John"

                print(s[::-1])    #Grab everything backwards as the stepsize is -1

                     => "nhoJ"

                print(s[1::2])    #Grab letters from the 1st index and increase by a stepsize of 2.

                     => "on"

        So keep in mind:    

    2. String Properties
        First of all, strings are immutability, which means once a string is created, its elements cannot be changed or replaced.
            s[0] = "K"  #This will occur an error!     
        But you can concatenate strings:
            print(s + "Lennon")
                => "John Lennon"
        You can also repeat a string by using a multiplication symbol:
            print(2*s)
                => "JohnJohn"
    3. Basic Built-in String Functions and Methods
       a) Functions
            You can determine the length of a string by using the len() function: 
                print(len(s))
                    => 4
       b) Methods
            You can convert all the characters in the string into uppercase or lowercase characters using upper() and lower() methods:        
                print(s.upper())
                    => "JOHN"
            By using split() method, you can split a string into a list of strings at specified separators.
                print("Hello World".split())
                    => ["Hello", "World"]

            

    

    

    

Comments