String In Python-

  • – When we create a string object then this string object will be created in String pool memory.
  • – Other than the string object will be created in Heap memory.

Ex-

class Demo:
    def __init__(self, a):
        self.a = a

class MainClass:
    def main():
        Obj1 = Demo(17)
        Obj2 = Demo(17)
        data1 = "simpleAlgo"
        data2 = "simpleAlgo"
        print(id(Obj1)) #4020
        print(id(Obj2)) #4020
        print(id(data1)) #2048
        print(id(data2)) #2048
        print(id(Obj1.a)) #1048
        print(id(Obj2.a)) #1048
        print("********")
        S3 = "simpleAlgo"
        print(S3.isalpha()) #True
        print(S3.isalnum()) #True
        print(S3.isdigit()) #False
MainClass.main()

Some Predefined Methods Of String –

  • – isalpha() – Return true if string contains alphabets only.
  • – isdigit() – Return if string contains any digit/numeric value only.
  • – isalnum() – Return true if string contains alphabets or numeric.
  • – ” or “” can be used to represent string.
  • – Indexing and slicing can be used to process the element of a string.
  • – With the help of index, we can process only 1charactor at a time.
  • – In case we want a set of characters or substring, we can use the concept of slicing.
  • – There is no concept of ‘char’ in python.
  • – Char is nothing but a string with length 1.
  • Index = 0 1 2 3 4 5
  • P y t h o n
  • Index = -6 -5 -4 -3 -2 -1
  • slicing- [LowerIndex : UperIndex]
  • (Included) (excluded)

Ex-

data1 = "simpleAlgo"
data2 = 'python'
print(data1) #simpleAlgo
print(data2)  #python
print(data1+data2) # simpleAlgopython

data3 = "Python"+str(3)
print(data3) #Python3
print("*************")
S4 = "Python"
print(S4[2]) #t
print(S4[-2]) #o
print(S4[1:3]) #yt
print(S4[:]) #python
print(S4[:4]) #pyth
print(S4[1:]) #ython
print(S4[2:-2]) #th

data = "simpleAlgo"
print("Hi-", data)
print("Hi- " + data)
print("Hi- %s" %data)

phoneNo = 1234567890
print(data, "phoneNo is", phoneNo)
print(data + " phoneNo is "+str(phoneNo))
print("%s phoneNo is %d" %(data, phoneNo))

salary = 25.2
print("salary is %f" %salary) #25.200000
print("salary is %2.3f" %salary) #25.200
print("salary is %d" %salary) #25
Menu