Monday, 13 March 2017

Str DataType in Python

str  DataType:

String:

  • Group of characters or sequence of characters is known as String.
  • We can represent the Strings in Python language by using single quotes (‘  ‘) or by using double quotes(“  “) or triple quotes(‘’’  ‘’’) and (“””   “””).
  • Single quotes are used to represent one line String.
  • Triple quotes are used to represent multiple lines.
  • Every character in the String Object is represented with unique index.
  • Python Strings are supporting both the +ve(Forward) indexing and –ve(Backward) indexing.
  • +ve index starts with 0(zero) whereas -ve index starts from -1.


Example1:

x= 'siva'

print(x)

y= "krishna"

print(y)

z= '''hai,

    this is siva krishna'''

print(z)


a= """ hai,

    welcome to my blog.

    tanq for follow my blog"""

print(a)

Output:

siva
Krishna

hai,
    this is siva Krishna


 hai,
    welcome to my blog.
    tanq for follow my blog.


Note:
  • Actually string (str) object is a immutable object, not modified. But reading the data by using indexes.

Example2:

s1="sivakrishna"

print(s1)

print(id(s1))

print(type(s1))

print(len(s1))

Output:

sivakrishna

55790896

<class 'str'>

11

Note:

  • len( ) is a pre-defined function in Builtin module.
  • Return the number of items/elements in a container/string.
  • Reading the data from the string by using indexes.


Example3:

s2="sivakrishna"

print(len(s2)) ---> return the number of characters in a given string.

print(s2[1]) ---> forward index, starting from 0

print(s2[-2]) ---> backward index, starting from -1

Output:

11

i

n



Python support slice(:) operator.

Syntax:
  • [n1:n2]  --- > n1 is lower bound value/n1 is a beginning index is inclusive and n2 is a upper bound value/n2 is a ending index is exclusive.
  • [n1: ] ---> n1 is lower bound value and up to ending value in a string.

Example4:

s3="sivakrishna"

print(s3)

print(len(s3))

print(s3[2:])

print(s3[2:5])

print(s3[-6:-2])

Output:

sivakrishna

11

vakrishna

vak

rish

Note:
  • First number is always lower limit.
  • Second number is always upper limit.

Example5:

s4="sivakrishna"

print(s4)

print(len(s4))

print(s4[3:1])

print(s4[-2:-6])

Output:

sivakrishna

11

No output

No output

Some other methods in string 

Example6:

a='siva'

b='KRISHNA'

print(a+b)

print(len(a))

print(a.upper())

print(b.lower())

print(a.startswith('si'))

print(b.startswith('kri'))

print(b.startswith('KRI'))

print(a.replace('siva','rama'))

print(b.replace('KRISHNA','seetha'))

Output:

sivaKRISHNA

4

SIVA

krishna

True

False

True

rama


seetha

No comments:

Post a Comment