Wednesday , June 19 2024
Python Strings - Accessing or update Values in Strings,

Python Strings

String in Python

Strings in Python :

Strings are used in Python to record text information, such as name. Strings in Python are actually a sequence, which basically means Python keeps track of every element in the string as a sequence. For example, Python understands the string “hello’ to be a sequence of letters in a specific order. This means we will be able to use indexing to grab particular letters (like the first letter, or the last letter).

This idea of a sequence is an important one in Python and we will touch upon it later on in the future.

In this lecture we’ll learn about the following:

1.) Creating Strings
2.) Printing Strings
3.) Differences in Printing in Python 2 vs 3
4.) String Indexing and Slicing
5.) String Properties
6.) String Methods
7.) Print Formatting

Creating a String

To create a string in Python you need to use either single quotes or double quotes. For example:

In [1]:
# Single word
In [2]:
# Entire phrase 
'This is also a string'
'This is also a string'
In [3]:
# We can also use double quote
"String built with double quotes"
'String built with double quotes'
In [4]:
# Be careful with quotes!
' I'm using single quotes, but will create an error'
  File "<ipython-input-4-3b26cff97c4c>", line 2
    ' I'm using single quotes, but will create an error'
SyntaxError: invalid syntax

The reason for the error above is because the single quote in I’m stopped the string. You can use combinations of double and single quotes to get the complete statement.

In [5]:
"Now I'm ready to use the single quotes inside a string!"
"Now I'm ready to use the single quotes inside a string!"

We can also use triple quotes. They function the same way as double and single qoutes.

In [6]:
"""This is a string with triple qoutes"""
'This is a string with triple qoutes'

Just like using double qoutes to use single qoutes without escape characters, we can do the same with double quotes and triple quotes. But its not optimal since you have to put an extra line in between them.

In [7]:
"""The man said "What is that going on over there!" """
'The man said "What is that going on over there!" '
In [8]:
"""The man said "What is that going on over there!""""
  File "<ipython-input-8-218d718bb158>", line 1
    """The man said "What is that going on over there!""""
SyntaxError: EOL while scanning string literal

Must add space

So just use the single quotes around double quotes first.

In [9]:
'There went "The Animal"'
'There went "The Animal"'

Escape characters. If there is some where situation where you need a bunch of quotes, you can use escape character \’ \’.
Just make sure you close the end of the string without the escape character .

In [10]:
'There went the man called \'Boaty McBoatFace\'' 
"There went the man called 'Boaty McBoatFace'"

Printing a String

Using Jupyter notebook with just a string in a cell will automatically output strings, but the correct way to display strings in your output is by using a print function.

In [11]:
# We can simply declare a string
'Hello World'
'Hello World'
In [12]:
# note that we can't output multiple strings this way
'Hello World 1'
'Hello World 2'
'Hello World 2'
In [13]:
print('Hello World')
print('Hello World')
Hello World
Hello World

The combination “\n” makes a newline appear in a string. You can use newlines anywhere you like in a string.

In [14]:
print("\nHello everyone!")
Hello everyone!
In [15]:
print("\tHello everyone!")
	Hello everyone!

String Basics

We can also use a function called len() to check the length of a string!

Sidenote: We can check the length of any data types that are collections with the same len() “call”.
It is considered a built-in function.

In [16]:
len('Machine Learning')

String Indexing

We know strings are a sequence, which means Python can use indexes to call parts of the sequence. Let’s learn how this works.

In Python, we use brackets [] after an object to call its index. We should also note that indexing starts at 0 for Python. Let’s create a new object called s and the walk through a few examples of indexing.

In [17]:
# Assign s as a string
s = 'Hello World'
In [18]:
'Hello World'
In [19]:
# Print the object
Hello World

Let’s start indexing!

In [20]:
s = ""
print(s)           # Prints complete string
print(s[0])        # Prints first character of the string
print(s[7:15])     # Prints characters starting from 3rd to 5th
print(s[7:])       # Prints string starting from 3rd character
print(s * 2)       # Prints string two times
print('www.' + s)  # Prints concatenated string
print(s[:])        # Prints complete string with range start to end
print(s[::])       # Prints complete string with range start to end with increment 1
print(s[::2])      # Print String with increment of 2
print(s[-1])       # print last character of a string
print(s[-3:])      # print last 3 character of a string

String Properties

Its important to note that strings have an important property known as immutability. This means that once a string is created, the elements within it can not be changed or replaced. Immuntiblity is a concept seen in other data types.

Immutability means that the data cannot mutate, aka the data cannot change. A new ‘data object’ needs to be created instead.

For example:

In [21]:
# Let's try to change the first letter to 'x'
s[0] = 'x'
TypeError                                 Traceback (most recent call last)
<ipython-input-21-976942677f11> in <module>
      1 # Let's try to change the first letter to 'x'
----> 2 s[0] = 'x'

TypeError: 'str' object does not support item assignment

Notice how the error tells us directly what we can’t do, change the item assignment!

Something we can do is concatenate strings!

In [22]:

Concatenate just means joining two strings together. Its a term used in other programming languages. But, don’t be scared about the terms.

In [23]:
# Concatenate strings!
s + ' concatenate me!'
' concatenate me!'
In [24]:
# We can reassign s completely though!
s = s + ' concatenate me!'
In [25]:
' concatenate me!'
In [26]:
print(s) concatenate me!

We can use the multiplication symbol to create repetition!

In [27]:
letter = 'z'
In [28]:

Basic Built-in String methods

Objects in Python usually have built-in methods. These methods are functions inside the object (we will learn about these in much more depth later) that can perform actions or commands on the object itself. To keep it brief, methods are actions that a ‘data thing’, aka an object like a string, can take. Functions are actions that belong to no ‘data thing’ aka object, and just exist in the program.

We call methods with a period and then the method name. Basically, we say ‘Hey object, do this to these things”. The things in question that we are asking the object to mess with are placed in the parameters.

Methods take the form:


Where parameters are extra arguments we can pass into the method. Don’t worry if the details don’t make 100% sense right now. Later on we will be creating our own objects and functions! But, to keep it brief, parameters represent what the action for the object should take. The arguments are the actual ‘data things’ that it needs to take.

Here are some examples of built-in methods in strings:

In [29]:
s="Machine Learning"
machine learning
In [30]:
In [31]:
s='this is a'
'This is a'
In [32]:
str='hello world, welcome to python tutorials'
print (,"-"))
----------hello world, welcome to python tutorials----------
In [33]:
s='this is a and wow!!!'
print (s.count('i',2,40)) #s.count(string,start,end)
print (s.count('wow'))

We can use the .format() method to add formatted objects to printed string statements.

The easiest way to show this is through an example:

In [34]:
print("My name is",Name,"and Age is",Age)
print("My Name is %s and Age is %d"%(Name,Age))
print("My Name is {} and Age is {}".format(Name,Age))
print("My Name is {0} and Age is {1}".format(Name,Age))
print("My Name is {1} and Age is {0}".format(Name,Age))
print(f"My Name is {Name} and age is {Age}")
print(f"My Name is {Name} and age is {Age} and Sum is {10+20}")
My name is Python and Age is 32
My Name is Python and Age is 32
My Name is Python and Age is 32
My Name is Python and Age is 32
My Name is 32 and Age is Python
My Name is Python and age is 32
My Name is Python and age is 32 and Sum is 30

Split Function

In [35]:
s="Welcome to Python"
['Welcome', 'to', 'Python']
In [36]:
['Welcome', 'to', 'Python']

Strip Function

In [37]:
s='      Python          '
In [38]:
s = '$Itronix#'
s = s.lstrip('$')
s = s.rstrip('#')
In [39]:
s = '$Itronix#'

About Machine Learning

Check Also

Python MySQL Insert Into Table

Python MySQL Insert Into Table

4 Python MySQL Insert Into Table Python MySQL Insert Into Table¶To fill a table in …

Leave a Reply

Your email address will not be published. Required fields are marked *