Class 7 - Data Types - String
Class 7 - Data Types - String
Ex:
A=“Hello Students!”
Print(“The length of string is”, len(A)
(Or)
str_length=len(A)
Print(“The length of string is”, len(A)
Slicing
a = "Hello Students"
print(a[2:7])
print(a[:7])
print(a[2:])
print(a[-2:-5])
print(a[-7:-2])
String Modification
a = "Hello, Students"
print(a.upper()) returns the string in upper case
print(a.lower()) returns the string in lower case
a = “ Hello, Students “
print(a.strip()) removes any whitespace from the
beginning or the end
print(a.replace("H", "J")) replaces a string with another
string
print(a.split(",")) splits the string into substrings if it finds
instances of the separator
String Concatenation
To concatenate, or combine, two strings you can
use the + operator.
a = "Hello"
b = "World"
c=a+b
print(c)
String Concatination - Continued
a = "Hello"
b = "World"
c=a+""+b
print(c)
Class Example 1
# This is a program about data types
var1 = 'This variable can be known as a string.'
# 0123456789
def type_value():
print(type(var1))
# finds the datatype of var 1
print(var1)
def length():
print(len(var1))
def var1_slice():
print(var1[0])
print(var1[0:4])
print(var1[:26])
print(var1[13:])
var1_slice()
# length()
# type_value()
Class Example 2
# This program is to explore more string functions
var1 = "Hello World!"
var2 = " Hello World,This is Shayaan!"
def sample_function():
print(var1.upper())
print(var1.replace("World", "Python"))
print(var2.split("66"))
print(var1+var2) #String Concatination
print(var2.strip())
sample_function()