Tuesday , March 19 2024
Python Strings - Accessing or update Values in Strings,

Python Strings

String in Python

Strings in Python : MachineLearning.org.in

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
'python'
Out[1]:
'python'
In [2]:
# Entire phrase 
'This is also a string'
Out[2]:
'This is also a string'
In [3]:
# We can also use double quote
"String built with double quotes"
Out[3]:
'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!"
Out[5]:
"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"""
Out[6]:
'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!" """
Out[7]:
'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"'
Out[9]:
'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\'' 
Out[10]:
"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'
Out[11]:
'Hello World'
In [12]:
# note that we can't output multiple strings this way
'Hello World 1'
'Hello World 2'
Out[12]:
'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')
Out[16]:
16

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]:
#Check
s
Out[18]:
'Hello World'
In [19]:
# Print the object
print(s) 
Hello World

Let’s start indexing!

In [20]:
s = "MachineLearning.org.in"
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
MachineLearning.org.in
M
Learning
Learning.org.in
MachineLearning.org.inMachineLearning.org.in
www.MachineLearning.org.in
MachineLearning.org.in
MachineLearning.org.in
Mcieerigogi
n
.in

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]:
s
Out[22]:
'MachineLearning.org.in'

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!'
Out[23]:
'MachineLearning.org.in concatenate me!'
In [24]:
# We can reassign s completely though!
s = s + ' concatenate me!'
In [25]:
s
Out[25]:
'MachineLearning.org.in concatenate me!'
In [26]:
print(s)
MachineLearning.org.in concatenate me!

We can use the multiplication symbol to create repetition!

In [27]:
letter = 'z'
In [28]:
letter*10
Out[28]:
'zzzzzzzzzz'

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:

object.method(parameters)

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"
print(s.upper())
print(s.lower())
print(s.swapcase())
print(len(s))
print(s.isupper())
print(s.islower())
print(s.isnumeric())
print(s.isdigit())
MACHINE LEARNING
machine learning
mACHINE lEARNING
16
False
False
False
False
In [30]:
print(max(s))
print(min(s))
r
 
In [31]:
s='this is a string...wow'
s.capitalize()
Out[31]:
'This is a string...wow'
In [32]:
str='hello world, welcome to python tutorials'
print (str.center(60,"-"))
----------hello world, welcome to python tutorials----------
In [33]:
s='this is a string..wow and wow!!!'
print (s.count('i',2,40)) #s.count(string,start,end)
print (s.count('wow'))
3
2

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]:
Name='Python'
Age=32
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"
s.split()
Out[35]:
['Welcome', 'to', 'Python']
In [36]:
s="Welcome-to-Python"
s.split('-')
Out[36]:
['Welcome', 'to', 'Python']

Strip Function

In [37]:
s='      Python          '
print(s)
print(s.strip())
print(s.lstrip())
print(s.rstrip())
      Python          
Python
Python          
      Python
In [38]:
s = '$Itronix#'
s = s.lstrip('$')
s = s.rstrip('#')
s
Out[38]:
'Itronix'
In [39]:
s = '$Itronix#'
s.lstrip('$').rstrip('#')
Out[39]:
'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 *