0% found this document useful (0 votes)
4 views1 page

Lesson 3 - Data Types in Python - Strings

The document provides an overview of strings in Python, highlighting their immutable nature and various operations such as creation, printing, indexing, slicing, and built-in methods. It explains how to create strings using single or double quotes, and demonstrates string manipulation techniques including concatenation and repetition. Additionally, it introduces string properties and methods like upper(), lower(), and split(), which are essential for handling text data in Python.

Uploaded by

Atharv Kulkarni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views1 page

Lesson 3 - Data Types in Python - Strings

The document provides an overview of strings in Python, highlighting their immutable nature and various operations such as creation, printing, indexing, slicing, and built-in methods. It explains how to create strings using single or double quotes, and demonstrates string manipulation techniques including concatenation and repetition. Additionally, it introduces string properties and methods like upper(), lower(), and split(), which are essential for handling text data in Python.

Uploaded by

Atharv Kulkarni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Strings

A String is a data structure in Python that represents a sequence of characters. It is an immutable data type, meaning that once you have created a string, you cannot change it. Strings are used widely in many different
applications, such as storing and manipulating text data, representing names, addresses, and other types of data that can be represented as text. 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.) String Indexing and Slicing 4.) String Properties 5.) String Methods 6.) Print Formatting

Creating a String
To create a string in Python, one can use either single inverted commas(' ') or double inverted commas(" "). For example:

In [3]: # Using single inverted commas with a single word.


x = 'Hello'
print(x)

Hello

In [4]: # Using double inverted commas with a single word.


y = "Hello"
print(y)

Hello

In [6]: # Using double inverted commas with a phrase.


phrase_var = "Good Morning People. Today's weather seems to be perfect for a dayout."
print(phrase_var)

Good Morning People. Today's weather seems to be perfect for a dayout.

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 [7]: # We can simply declare a string


'Hello Python'

'Hello Python'
Out[7]:

In [8]: # Note that we can't output multiple strings this way


'Hello Python'
'Hello Java'

'Hello Java'
Out[8]:

We can use a print statement to print a string. "\n" is used to move to the next line and "\t" is used to give 5 spaces, that is a tab space.

In [9]: print('Hello Python')


print('\n')
print('Hello \t\t Java')

Hello Python

Hello Java

String Basics
We can also use a function called len() to check the length of a string. Python's built-in len() function counts all of the characters in the string, including spaces and punctuation.

In [10]: print("You're a Wizard, Harry!")


len("You're a Wizard, Harry!")

You're a Wizard, Harry!


23
Out[10]:

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 then walk through a few examples of indexing.

In [18]: # Assign var as a string


var = "You're a Wizard, Harry!"
print(var)

You're a Wizard, Harry!

In [12]: var[0]

'Y'
Out[12]:

In [13]: var[6:]

' a Wizard, Harry!'


Out[13]:

In [14]: var[:18]

"You're a Wizard, H"


Out[14]:

In [ ]: """
Note the above slicing. Here we're telling Python to grab everything from 0 up to 3. It doesn't include the 3rd index.
You'll notice this a lot in Python, where statements and are usually in the context of "up to, but not including".
"""

In [15]: var[4:9]

're a '
Out[15]:

In [19]: var[:-1] # Grab everything but the last letter

"You're a Wizard, Harry"


Out[19]:

In [17]: var[::-1] # We can use this to print a string backwards

"!yrraH ,draziW a er'uoY"


Out[17]:

In [20]: var[::2] # Grab everything, but go in step sizes of 2

'Yur iad ar!'


Out[20]:

String Properties
It's 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. For example:

In [23]: s = 'Hello World'

In [22]: s[0] = 'x' # Let's try to change the first letter to 'x'

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[22], line 1
----> 1 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 [24]: s + ' ' + 'Elpro' # Concatenate strings!

'Hello World Elpro'


Out[24]:

In [25]: s = s + ' concatenate me!' # We can reassign s completely though!


print (s)

Hello World concatenate me!

We can use the multiplication symbol to create repetition!

In [27]: letter = 'z'


print(letter)
rep = letter*10
print(rep)

z
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.

We call methods with a period and then the method name. Methods are in 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!

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

In [29]: var.upper() # Upper Case a string

"YOU'RE A WIZARD, HARRY!"


Out[29]:

In [30]: var.lower() # Lower Case a string

"you're a wizard, harry!"


Out[30]:

In [31]: result = var.split(" ") # Split a string by blank space (this is the default)
print(result)

["You're", 'a', 'Wizard,', 'Harry!']

In [32]: s = "Hello \tworld \tthat one is the flashy green card"


s.split("\t")

['Hello ', 'world ', 'that one is the flashy green card']
Out[32]:

In [33]: r = "Hey, How are you!"


r.split(',')

['Hey', ' How are you!']


Out[33]:

In [34]: r = "Hey, How are you!" # Split by a specific element (doesn't include the element that was split on)
r.split('w')

['Hey, Ho', ' are you!']


Out[34]:

In [35]: sample = ["Elpro","School"]


output = "#".join(sample)
#Joining a string to another string by using var.join('arg'), where 'var' is the string to be joined to 'arg'.
print(output)

Elpro#School

You might also like