Python Strings (1)
Python Strings (1)
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
It's alright
He is called 'Johnny'
He is called "Johnny"
1
1.1.2 Assign string to a variable
[7]: a = "Hello"
print(a)
Hello
[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.
"""
print(a)
[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.
'''
print(a)
2
[12]: a = "Hello World"
print(a[0])
[13]: print(a[1])
[14]: print(a[-1])
a
p
p
l
e
11
19
True
3
1.1.8 to check if not
[20]: txt = "The best things in life are free"
print("expensive" not in txt)
True
[23]: print(b[2:5])
llo
Hello
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
loc ndCrgTmr ot
String Reverse
[31]: a = "Tiger Coding School"
print(a[::-1])
[33]: print(a.lower())
capitalize() The capitalize() method returns the first character of string in upper case.
[34]: print(a.capitalize())
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
hello universe
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:
6
['Hello', ' World']
Sting Concatenation
[47]: a = "Hello"
b = "World"
c = a + b
print(c)
HelloWorld
Hello World
The + Operator
• – operator concatenates strings
[41]: s = 'strawberry'
i = 'ice'
c = 'cream'
print(s + i)
print(s + i + c)
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)
But we can combine strings and numbers by using f-strings or the format() method!
[51]: age = 40
txt = f"My name is john, I am {age}"
print(txt)
My name is john, I am 40
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)
price = 50
txt = f"The price is {price:.2f} dollars"
print(txt)
[35]: # Perform a math operation in the placeholder, and return the result.
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."
[57]: txt = "We are the so-called 'Humans' from the earth."
print(txt)
[58]: txt = "We are the so-called \"Humans\" from the earth."
print(txt)
9
We are the so-called "Humans" from the earth.
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
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
11
1.4 Quiz link
https://quizizz.com/join?gc=443372
[ ]:
12