0% found this document useful (0 votes)
2 views7 pages

7.Python Strings

The document provides an overview of strings in Python, including how to create, assign, and manipulate them. It covers topics such as string concatenation, formatting, checking for substrings, and using escape characters. Additionally, it explains string slicing and the use of the len() function to determine string length.

Uploaded by

venkatesh
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)
2 views7 pages

7.Python Strings

The document provides an overview of strings in Python, including how to create, assign, and manipulate them. It covers topics such as string concatenation, formatting, checking for substrings, and using escape characters. Additionally, it explains string slicing and the use of the len() function to determine string length.

Uploaded by

venkatesh
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/ 7

Python Strings

Strings in python are surrounded by either single quotation marks, or double


quotation marks.
'hello' is the same as "hello"
Example
In [1]: print("Hello")
print('Hello')

Hello
Hello

Assign String to a Variable


Assigning a string to a variable is done with the variable name followed by an
equal sign and the string
Example
In [2]: a = "Hello"
print(a)

Hello

Multiline Strings
You can assign a multiline string to a variable by using three quotes
Example
You can use three double quotes
In [3]: a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.

Or you can use three single quotes


Example
In [4]: a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)

Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.

Note: in the result, the line breaks are inserted at the same position as in the
code

Strings are Arrays


Like many other popular programming languages, strings in Python are arrays of
bytes representing unicode characters.
However, Python does not have a character data type, a single character is
simply a string with a length of 1.

Square brackets[ ] can be used to access elements of the string


Example
Get the character at position 1 (The first character has the position 0)
In [8]: a = "Hello, World!"
print(a[1])

String Length
To get the length of a string, use the len() function
Example
In [9]: a = "Hello, World!"
print(len(a))

13

Check String
To check if a certain phrase or character is present in a string, we can use the
keyword * in
Example
Check if "free" is present in the following text
In [10]: txt = "The best things in life are free!"
print("free" in txt)
True

Use it in an if statement
Example
Print only if * "free" * is present
In [13]: txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")

Yes, 'free' is present.

Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use
the keyword not in
Example
Check if "expensive"
is NOT present in the following text
In [12]: txt = "The best things in life are free!"
print("expensive" not in txt)

True

Use it in an if statement
Example
print only if "expensive" is NOT present
In [3]: txt = "The best things in life are free!"
if "expensive" not in txt:
print("No, 'expensive' is NOT present.")

No, 'expensive' is NOT present.

Slicing Strings
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part
of the string
Example
Get the characters from position 2 to position 5 (not included)
In [2]: b = "Hello, World!"
print(b[2:5])

llo
Note: The first character has index 0

Slice From the Start


By leaving out the start index, the range will start at the first character
Example
Get the characters from the start to position 5 (not included)
In [1]: b = "Hello, World!"
print(b[:5])

Hello

Slice To the End


By leaving out the end index, the range will go to the end:
Example
Get the characters from position 2, and all the way to the end
In [4]: b = "Hello, World!"
print(b[2:])

llo, World!

Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example
Get the characters:
From: "o" in "World!" (position -5)
To, but not included: "d" in "World!" (position -2)
In [5]: b = "Hello, World!"
print(b[-5:-2])

orl

String Concatenation
To concatenate, or combine, two strings you can use the + operator.
Example
Merge variable a with variable b into variable c
In [6]: a = "Hello"
b = "World"
c = a + b
print(c)

HelloWorld
Example
To add a space between them, add a " "
In [7]: a = "Hello"
b = "World"
c = a + " " + b
print(c)

Hello World

String Format
we cannot combine strings and numbers
Example
In [8]: age = 36
txt = "My name is John, I am " + age
print(txt)

------------------------------------------------------------------------
---
TypeError Traceback (most recent call la
st)
Cell In[8], line 2
1 age = 36
----> 2 txt = "My name is John, I am " + age
3 print(txt)

TypeError: can only concatenate str (not "int") to str

But we can combine strings and numbers by using the format() method!
The format() method takes the passed arguments, formats them, and places
them in the string where the placeholders {} are
Example
Use the format() method to insert numbers into strings
In [9]: age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

My name is John, and I am 36

The format() method takes unlimited number of arguments, and are placed into
the respective placeholders
Example
In [12]: quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

I want 3 pieces of item 567 for 49.95 dollars.

You can use index numbers {0} to be sure the arguments are placed in the
correct placeholders
Example
In [13]: quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

I want to pay 49.95 dollars for 3 pieces of item 567.

if you want to refer to the same value more than once, use the index number
Example
In [14]: age = 36
name = "John"
txt = "His name is {1}. {1} is {0} years old."
print(txt.format(age, name))

His name is John. John is 36 years old.

Named Indexes
You can also use named indexes by entering a name inside the curly brackets
{carname}, but then you must use names when you pass the parameter values
txt.format(carname = "Ford")
Example
In [16]: myorder = "I have a {carname}, it is a {model}."
print(myorder.format(model = "Mustang", carname = "Ford"))

I have a Ford, it is a Mustang.

Escape Character
To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash \ followed by the character you want to
insert.
An example of an illegal character is a double quote inside a string that is
surrounded by double quotes
Example
You will get an error if you use double quotes inside a string that is
surrounded by double quotes
In [17]: txt = "We are the so-called "Vikings" from the north."

Cell In[17], line 1


txt = "We are the so-called "Vikings" from the north."
^
SyntaxError: invalid syntax

To fix this problem, use the escape character


Example
In [23]: # Double Quotes \"
txt = "We are the so-called \"Vikings\" from the north."
print(txt)

We are the so-called "Vikings" from the north.

In [22]: # Single Quote \'


txt = 'We are the so-called \'Vikings\' from the north.'
print(txt)

We are the so-called 'Vikings' from the north.

In [28]: # Backslash \\
print("HelloWorld\\")

HelloWorld\

In [20]: # Carriage Return \r


print("Hello\rWorld")

World

In [29]: # New Line \n


print("Hello\nWorld")

Hello
World

In [30]: # Octal value \ooo


print("\123\145\160\164\145\155\142\145\162")

September

In [31]: # Hex value \xhh


print("\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64")

Hello World

In [32]: # Tab \t
print("Hello\tWorld")

Hello World

In [33]: # Backspace \b
print("Hello\bWorld")

HellWorld

You might also like