. String Operations
[2]:
123
# String can be made with both double and single quotes
str1="Hello world"
str2 ='Hello World'[3]:
123
# if a string already contains single quote use double quote to enclose it and vice versa
str1 ="Hello' World"
print(str1)stdout
Hello' World
[4]:
12345
# Accessing string from index
str1 = "Hello World"
print("First char in string",str1[0]) # first index of the string
print("Last charecter in string",str1[-1]) # last index of the string
stdout
First char in string H
Last charecter in string d
[5]:
12
# Slicing a string( get char between 2nd and 7th index)
print(str1[2:7])stdout
llo W
[6]:
12
# String are immutable in python
str1[4]='a' # this will throw an error---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_33492\2280378761.py in <module>
1 # String are immutable in python
----> 2 str1[4]='a' # this will throw an error
TypeError: 'str' object does not support item assignment
[7]:
1234
# use triple quotes for multiline string
str1 ="""hello world
python is the best programming language"""
print(str1)stdout
hello world
python is the best programming language
[9]:
123456
#Compare two string
str1="Hello world"
str2="Python is best"
str3="Hello world"
print(str1==str2)
print(str1==str3)stdout
False
True
[11]:
12
# Concatenate two or more string
print(str1+' '+str2)stdout
Hello world Python is best
[14]:
123456
# loop through a string (below code will check if a is present in the string)
str1='python is a procedural programmin language'
for i in str1:
if i=='a':
print("a is present")
breakstdout
a is present
[ ]:
1234
str1="Hello world"
for idx,val in enumerate(str1):
if val=='o':
print("o is present",idx)[15]:
12
# get length of a string
len(str1)Out[15]:
42
[16]:
123
# Membership test(check if a particular charecter is present in the string or not)
print('a' in str1)
print('z' in str1)stdout
True
False
[17]:
12345
# upper ,lower(),capitalize(),replace()
print(str1.upper())
print(str1.lower())
print(str1.capitalize())
print(str1.replace('a','z'))stdout
PYTHON IS A PROCEDURAL PROGRAMMIN LANGUAGE
python is a procedural programmin language
Python is a procedural programmin language
python is z procedurzl progrzmmin lznguzge
[21]:
123456
# startswith(),isnumeric(),endswith(),islapha()
print(str1.startswith('pyth'))
print(str1.endswith('za'))
print(str1.isnumeric())
print('123'.isnumeric())
print('123'.isalpha())stdout
True
False
False
True
False
[24]:
1234567
#Exercise 1 - find out total numeric charecters in the below string
str1="World crude steel production for the 71 countries reporting to the World Steel Association (worldsteel) was 155.7 million tonnes (Mt) in April 2024, a 5.0% decrease compared to April 2023."
numeric_count=0
for i in str1:
if i.isnumeric():
numeric_count+=1
print("Total numeric values in string are ",numeric_count)stdout
Total numeric values in strings are 16
[26]:
123
# Formatting string
print(f"Total numeric values in string are {numeric_count}") # if we write f at the start of the string we can use the variables
# in curly bracesstdout
Total numeric values in string are 16
[28]:
1234
# raw format
print("hello python is \n best programming language") # notice a new line in the output due to \n
print(r"hello python is \n best programming language") # the new line will not be present now and \n will be printed as is
stdout
hello python is
best programming language
hello python is \n best programming language
[29]:
12
# index of a char in string
str1.index('a') # return the first index of a char in a stringOut[29]:
85
[31]:
12345
# remove extra spaces from start or end or both of a string
str1=" Hello world "
print(str1.lstrip())
print(str1.rstrip())
print(str1.strip())stdout
Hello world
Hello world
Hello world
[32]:
123
# spillitng a string basis a special charecter
str1 ="apple, mango,banana,orange"
str1.split(',') # retruns a list typeOut[32]:
['apple', ' mango', 'banana', 'orange']
[34]:
1234
# Exercise 2 split string on the basis of comma and remove spaces in each substring and print it
str1 ="apple, mango,banana,orange"
for i in str1.split(','):
print(i.strip())stdout
apple
mango
banana
orange
[36]:
1234
# Reverse a string
print(str1)
print(str1[::-1])
stdout
apple, mango,banana,orange
egnaro,ananab,ognam ,elppa
[40]:
12345678
# Exercise 3 below string has fruit names seperated by comma , modify the string such that order of the fruits is reversed
# but individual name of the fruit should remain same
str1 ="apple, mango,banana,orange"
new_String=''
for i in str1[::-1].split(','):
new_String = new_String+','+i[::-1]
new_String=new_String[1:]
new_StringOut[40]:
'orange,banana, mango,apple'
[41]:
12
#Exercise 4 get last 3 charecter of a string
str1[-3:]Out[41]:
'nge'
[42]:
12
#Exercise 4 get all charecters of a string after 4th index
str1[4:]Out[42]:
'e, mango,banana,orange'
[45]:
123
# join() function in list of string (if you have a list of strings you can join then by a seperator as below)
str_list =["apple","mango","banana","orange"]
"|".join(str_list) # fruits will be replaced by our chosen charecterOut[45]:
'apple|mango|banana|orange'
[47]:
123
# Chain string method
string = " Hello, World! "
string.strip().lower().replace("world", "Python")Out[47]:
'hello, Python!'
[ ]:
1