0% found this document useful (0 votes)
4 views

Python Strings (1)

This document provides a comprehensive overview of Python strings, covering topics such as string creation, slicing, modification, concatenation, formatting, and various string methods. It includes examples and explanations of string operations, including checking for substrings, string length, and using escape characters. Additionally, it presents exercises and homework questions to reinforce learning about string manipulation in Python.

Uploaded by

Raj Raj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Strings (1)

This document provides a comprehensive overview of Python strings, covering topics such as string creation, slicing, modification, concatenation, formatting, and various string methods. It includes examples and explanations of string operations, including checking for substrings, string length, and using escape characters. Additionally, it presents exercises and homework questions to reinforce learning about string manipulation in Python.

Uploaded by

Raj Raj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Python Strings

January 31, 2025

1 Strings
• Python Strings
• Slicing strings
• Modifying strings
• Concatenate strings
• Format strings
• Escape characters
• String methods / inbuilt functions
• String Exercises

1.1 Strings
• Strings in python are surrounded by either single quotation marks, or double quotation marks.
• ‘hello’ is the same as ”hello
• You can display a string literal with the print() functio
• You can use quotes inside a string as long as they don’t match the quotes surrounding the
string.
• Lets see the examplesple
[1]: print('Hello World')
print("Hello World")

Hello World
Hello World

1.1.1 Qutoes inside quotes

[5]: print("It's alright")

It's alright

[6]: print("He is called 'Johnny'")


print('He is called "Johnny"')

He is called 'Johnny'
He is called "Johnny"

1
1.1.2 Assign string to a variable

[7]: a = "Hello"
print(a)

Hello

1.1.3 Multiline strings

[9]: a = """Jupyter Notebooks provide a web-based interface for creating and sharing␣
↪computational documents.

You can seamlessly mix executable code, documentation, and instructions in one␣
↪portable document.

Anaconda Notebooks is a hosted JupyterLab service that enables you to run␣


↪JupyterLab notebooks reliably online.

"""
print(a)

Jupyter Notebooks provide a web-based interface for creating and sharing


computational documents.
You can seamlessly mix executable code, documentation, and instructions in one
portable document.
Anaconda Notebooks is a hosted JupyterLab service that enables you to run
JupyterLab notebooks reliably online.

[11]: a = '''Jupyter Notebooks provide a web-based interface for creating and sharing␣
↪computational documents.

You can seamlessly mix executable code, documentation, and instructions in one␣
↪portable document.

Anaconda Notebooks is a hosted JupyterLab service that enables you to run␣


↪JupyterLab notebooks reliably online.

'''
print(a)

Jupyter Notebooks provide a web-based interface for creating and sharing


computational documents.
You can seamlessly mix executable code, documentation, and instructions in one
portable document.
Anaconda Notebooks is a hosted JupyterLab service that enables you to run
JupyterLab notebooks reliably online.

1.1.4 Strings as Arrays


• Strings are stored as arrays
• And each character in string are having index value starting from
• From the end the index value starts from -1.

2
[12]: a = "Hello World"
print(a[0])

[13]: print(a[1])

[14]: print(a[-1])

1.1.5 Looping through a string

[15]: for x in "apple":


print(x)

a
p
p
l
e

1.1.6 string length

[16]: a = "Hello World"


print(len(a))

11

[17]: b = "Tiger Coding School"


print(len(b))

19

1.1.7 to check string

[18]: txt = "The best things in life are free"


if "free" in txt:
print("Yes, 'free' is present.")

Yes, 'free' is present.

[19]: txt = "The best things in life are free"


print("free" in txt)

True

3
1.1.8 to check if not
[20]: txt = "The best things in life are free"
print("expensive" not in txt)

True

[21]: txt = "The best things in life are free"


if "expensive" not in txt:
print("No, 'expensive' is not present.")

No, 'expensive' is not present.

1.1.9 String Slicing


• 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.
[22]: b = "Hello World"
print(b[0])

[23]: print(b[2:5])

llo

Slice from the start


[24]: b = "Hello World"
print(b[:5])

Hello

Slice to the end


[25]: b = "Hello World"
print(b[2:])

llo World

Negative indexing
[26]: b = "Hello World"
print(b[-5:-2])

Wor

[27]: print(b[-11:-6])

Hello

4
Skipping 1 character
[28]: a = "We are here to learn python from Tiger Coding School"
print(a[0:30:2])

W r eet er yhnf

[29]: a = "We are here to learn python from Tiger Coding School"
print(a[0:30:3])

Wa rtlrph

Skipping 1 character from the last


[30]: a = "We are here to learn python from Tiger Coding School"
print(a[-1:-30:-2])

loc ndCrgTmr ot

String Reverse
[31]: a = "Tiger Coding School"
print(a[::-1])

loohcS gnidoC regiT

1.1.10 String Modifying


upper() The upper() method returns the string in upper case.

[32]: a = "Tiger Coding School"


print(a.upper())

TIGER CODING SCHOOL

lower() The lower() method returns the string in lower case.

[33]: print(a.lower())

tiger coding school

capitalize() The capitalize() method returns the first character of string in upper case.

[34]: print(a.capitalize())

Tiger coding school

title() The title() method returns the frist character of each word in the string in upper case.

[35]: print(a.title())

5
Tiger Coding School

replace() function The replace() method replaces a string with another string

[37]: a = "hello world"


print(a.replace("world", "universe"))

hello universe

[38]: a = "hello world"


print(a.replace("h","j"))

jello world

count() function
[39]: a = "hello world"
print(a.count('o'))

endswith() function
[41]: a = "Hello World"
print(a.endswith('l'))

False

starswith() function
[43]: a = "Hello World"
print(a.startswith('H'))

True

strip() - Remove whitespace The strip() method removes any whitespace from the beginning
or the end:
[44]: a = " Hello World "
print(a.strip())

Hello World

Split string
• The split() method returns a list where the text between the specified separator becomes the
list items.
• The split() method splits the string into substrings if it finds instances of the separator:

[46]: a = "Hello, World"


print(a.split(","))

6
['Hello', ' World']

Sting Concatenation
[47]: a = "Hello"
b = "World"
c = a + b
print(c)

HelloWorld

[48]: d = a + " " + b


print(d)

Hello World

The + Operator
• – operator concatenates strings
[41]: s = 'strawberry'
i = 'ice'
c = 'cream'

print(s + i)
print(s + i + c)

print('Go team' + '!!!')

strawberryice
strawberryicecream
Go team!!!

The * Operator
• – operator creates multiple copies of the string
[49]: a = "Hello"
print(a*5)
print(5*a)

HelloHelloHelloHelloHello
HelloHelloHelloHelloHello

The in operator
• The in operator returns true if the first operand is contained in within second or returns false
[50]: f = 'fruit'

7
f in 'Apple is a fruit'

#f in 'Apple is a vegetable'

[50]: True

Sting Format
[50]: age = 40
txt = "My name is John, I am" + age
print(txt)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[50], line 2
1 age = 40
----> 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 f-strings or the format() method!

F-Strings / Format strings


• F-String was introduced in Python 3.6, and is now the preferred way of formatting strings.
• To specify a string as an f-string, simply put an f in front of the string literal, and add curly
brackets {} as placeholders for variables and other operations.

[51]: age = 40
txt = f"My name is john, I am {age}"
print(txt)

My name is john, I am 40

[29]: sound = "Bark"

print(f'A dog says {sound}!')


print(f"A dog says {sound}!")
print(f'''A dog says {sound}!''')

A dog says Bark!


A dog says Bark!
A dog says Bark!

Placeholders and Modifiers A placeholder can contain variables, operations, functions, and
modifiers to format the value.

8
[31]: # Add a placeholder for the price variable

price = 50
txt = f"The price is {price} dollars"
print(txt)

The price is 50 dollars


A placeholder can include a modifier to format the value.
A modifier is included by adding a colon : followed by a legal formatting type, like .2f which means
fixed point number with 2 decimals:
[33]: # Display the price with 2 decimals

price = 50
txt = f"The price is {price:.2f} dollars"
print(txt)

The price is 50.00 dollars

[35]: # Perform a math operation in the placeholder, and return the result.

txt = f"The price is {20 * 59} dollars"


print(txt)

The price is 1180 dollars

Escape characters
• 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 insertorth.
[55]: txt = "We are the so-called "Humans" from the earth."

Cell In[55], line 1


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

[57]: txt = "We are the so-called 'Humans' from the earth."
print(txt)

We are the so-called 'Humans' from the earth.

[58]: txt = "We are the so-called \"Humans\" from the earth."
print(txt)

9
We are the so-called "Humans" from the earth.

1.1.11 String Functions / Methods


• chr() - converts an integer to a character
• ord() - converts a character to an integer
• len() - Returns the length of a string
• str() - Returns a string representation of an object.

ord() function
[59]: ord('a')

[59]: 97

[60]: ord('$')

[60]: 36

chr() function
[61]: chr(97)

[61]: 'a'

[62]: chr(36)

[62]: '$'

len() function
• returns the length of a string.
[62]: s = "I am a super power"
len(s)

[62]: 18

1.1.12 Boolean sting function


isaplpha()
[66]: a = "HelloWorld"
print(a.isalpha())

True

isalnum()

10
[67]: a = "Hello123"
print(a.isalnum())

True

isspace()
[68]: a = " "
print(a.isspace())

True

isdigit()
[69]: a = "12345"
print(a.isdigit())

True

isupper()
[70]: a = "TIGER CODING SCHOOL"
print(a.isupper())

True

islower()
[71]: a = "tiger coding school"
print(a.islower())

True

1.2 Exercise question


Write a program to get an output like this s1 = “You” s2 = “Have” s3 = “Done” s4 = “Good Job”
output = “You Have Done Good Job”
S = “This is a class on Python” Apply all the string functions on this string. Like : upper ,lower
,title , replace,count,endswith, startswith
These functions will return true or false.
print(“A” in “Apple”)

1.3 Homework questions


• Print First name, middle name, last name by getting input from the user side.
• Python program to check whether the string is Symmetrical or Palindrom
• Reverse words in a given String in Python

11
1.4 Quiz link
https://quizizz.com/join?gc=443372

[ ]:

12

You might also like