Strings
A string is a sequence of characters it could be either words, sentence or
paragraph enclosed in either single quotes (' ') or double quotes (" ").
It is used to store the textual information.
For multiple lines we use triple quotes (“”” “””)
x = "John"
# is the same as
x = 'John'
sen= 'deeplearning sits at the heart of GenerativeAI'
print(sen)
// deeplearning sits at the heart of GenerativeAI
type(sen)
//Str
# We can also use double quote
abc = "String built with double quotes"
print(abc) # Use the print command
String built with double quotes
# Be careful with quotes!
st= 'I'm ravi ,i want to become a data scientist'
print(st)
Output:
Cell In[30], line 3
st= 'I'm ravi ,i want to become a data scientist'
^
SyntaxError: invalid syntax
st1= "I'm ravi ,i want to become a data scientist"
print(st1)
We can use the print() statement to print
multiple inputs
a="ravi"
b="data scientist"
c="Hyderabad"
print(a)
print(b)
print(c)
Output: ravi
data scientist
Hyderabad
print("Hello",1,3,4,5.6,True,False)
Hello 1 3 4 5.6 True False
print("Hello",1,3,4,5.6,True,False,sep=“ ") print("A", "B", "C", sep=",") # A,B,C
print("A", "B", "C", sep="-") # A-B-C
Hello 1 3 4 5.6 True False print("A", "B", "C", sep="\n") # A
print("Hello",1,3,4,5.6,True,False,sep="*") #B
#C
Hello*1*3*4*5.6*True*False
print("Hello",1,3,5,5.6,True,False, sep="-")
Hello-1-3-5-5.6-True-False
why this is printing one by one ?
# because of after completing each input it prints next
new line by default in python end='/n'
print("laxman")
print("kota")
laxman
kota
print("laxman", end=' ')
print("kota")
laxman kota
print("laxman", end='+')
print("kota")
laxman+kota
print()
what is the issue here
x=5
y = "John"
print(x + y)
----------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[16], line 3
1x=5
2 y = "John"
----> 3 print(x + y)
TypeError: unsupported operand type(s) for +: 'int' and 'str’
x=5
y = "John"
print(str(x) + y)
5John
x=5
String Indexing
Indexing is the process of accessing individual characters in a string using their
position (index). In most programming languages like Python, string indexing starts
at 0, meaning the first character has index 0, the second has index 1, and so on.
In Python, we use brackets [] after an object to call its index.
text = "Python"
print(text[0]) # Output: P
print(text[3]) # Output: h
print(text[-1]) # Output: n (last character)
st="we are learning python"
print(st[0]) #w
print(st[4]) #r
print(st[-2]) #o
print(len(st))
print(st[22])
Traceback (most recent call last):
File "c:\Users\saina\OneDrive\Desktop\python\
ex1.py", line 6, in <module>
print(st[22])
~~^^^^
IndexError: string index out of range
String slicing
String slicing in Python means extracting a portion (substring) of a
string using index positions.
Syntax:
string[start : end : step]
•start: Starting index (inclusive)
•end: Ending index (exclusive)
•step: (optional) The interval or jump between characters how many characters to skip
while slicing.
abc="Deep learning is subset of machine learning"
print(abc[0:5]) # prints "Deep "
print(abc[6:12]) # prints "learning"
print(abc[13:20]) # prints "is subset"
print(abc[:]) # 'Deep learning is subset of machine learning'
print(abc[0:]) # 'Deep learning is subset of machine learning’
print(abc[:43]) # ending value n-1
'Deep learning is subset of machine learning’
abc='Deep learning is subset of machine learning'
print(abc[0::1])
Deep learning is subset of machine learning
print(abc[0:43:1])
Deep learning is subset of machine learning
print(abc[0:43:2])
De erigi usto ahn erig
print(abc[0:43:3])
Dpengsueomheeng
Reverse of string
abc='Deep learning is subset of machine learning’
print(abc[::-1])
'gninrael enihcam fo tesbus si gninrael peeD'
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 via item assignment. We will see how we can do such operation using string
methods
# Can we change our string 'Hello' to 'Cello'? Lets try replacing the first letter H with C
s='Hello'
s[0] = ‘C’
print(s)
----------------------------------------------------------------------
TypeError Traceback (most recent call
last)
Cell In[5], line 3
1 # Can we change our string 'Hello' to 'Cello'? Lets try
replacing the first letter H with C
2 s='Hello'
----> 3 s[0] = 'C'
TypeError: 'str' object does not support item assignment
concatenate strings
# Concatenate strings!
st1='Raju'
st2='king'
print(st1 + st2 ) #Rajuking
print(st1 +“ "+ st2) #Raju king
hai1="ganesh"
hello2="ram_singh"
print(hai1+" "+hello2) #ganesh ram_singh
print(hai1 +4 +hello2) # we can't concatenate string and numbers
String functions and methods:
1. len():
len() function returns the length of the string
Example:
key="hai this is ganesh iam from nizamabad"
print(len(key))
#38
methods:
1. lower()
lower() method converts the string to
lowercase
Example:
abc='HELLO-WORLD'
print(abc.lower()) #hello-world
2. upper()
upper() method converts the string to
uppercase
Example:
abc='hello-world'
print(abc.upper()) #HELLO-WORLD
ij="sabik is working from india“
3. capitalize()
ij.capitalize()
'Sabik is working from india’
4. title()
ij.title()
'Sabik Is Working From India’
5. swapcase()
"KoLkAtA".swapcase()
'kOlKaTa'
5. count()
count() method returns the count of a string in the given string
bc_d1 = 'Deep Neural Networks’
Print(bc_d1.count("Ne"))
2
Print(bc_d1.count("e"))
4
Print(bc_d1.count(" "))
2
Print(bc_d1.count("Deep"))
1
isalnum/ isalpha/ isdigit
b="Flat“ b="FLAT20&"
b.isalpha() //True b.isalnum() //False
c="Flat20" e="20"
c.isalpha() //False e.isdigit() //True
d="Flat20" f="flat20"
d.isalnum() //True f.isdigit() //False
b="Flat"
b.isalnum() //True
x="35"
x.isalnum() //True
Split():
split() function in Python is used to split a string into a list based on a delimiter (default is
whitespace).
ab="who is the pm of india"
ab.split()
['who', 'is', 'the', 'pm', 'of', 'india']
data = "apple,banana,cherry"
items = data.split(",")
print(items)
.join():
The .join() method in Python is used to combine elements of a list (or any iterable)
into a single string, with a specified separator between each element.
de=['who', 'is', 'the', 'pm', 'of', 'india']
" ".join(de)
'who is the pm of india'
"@".join(de)
'who@is@the@pm@of@india'
"*".join(de)
'who*is*the*pm*of*india'