Skip to main content

Notes - 12/21/20

12/21/20 Monday

Day 2 of working on the Udemy Python Bootcamp course! We're going to pickup with more info about strings.

String Properties and Methods

Strings are "immutable" or cannot be changed. So for example:

  • If I set name = "Bob"
  • And then I try to set 'B' to 'R', I'm not allowed to. I'll get an error.

Concatenate

If I do want to change that 0 position, I will have to use concatenation.

  1. Slice out the parts of the string I want to keep by creating a new string based on the first string. So in this case, I wan't to create the string "last_letters" based on "name".
  2. Concatenate using + so I would take the "last_letters" and then Concatenate "R" to make Rob.
  • last_letters = name[1:]
  • 'R' + last_letters

Using Concatenate is a way to put strings together. I can also add a variable to a string and run the cell to generate a longer statement.

x = 'Hello World'
x = x + ' it is nice out`
x

So the first run would say "Hello World it is nice out". And running the cell again would add on more "it is nice out". Concatenate could be added or multiplied. Remember that it's easy to confuse integers and strings. This is a con of the flexibility of the dynamic typing in Python. For example:

  • 2+3 will yield 5
  • "2"+"3" will Concatenate the strings "2" and "3" and yield 23

Functions

Variables can be modified with Python built in functions. First, define the variable as a string. In my example, I want x = 'Hello World'.

Now if I type x. in VSCode, a list of functions will appear. Syntax for these functions are variable.function(). If you don't include (), then Python will think you're just asking what that function will do.

Example of functions include:

  • upper for all upper case letters in the string
  • lower for all lower case letters in the string
  • split will take your string and turn it into a list. The default split will divide the string at each whitespace. I can tell split where to split the list up.

Important Note: Comments

To add comments to my code, create a line that begins with # then write the comment out.