Thursday, June 22, 2023

Python Strings

 

                               PYTHON STRINGS

A string is a sequence of characters.

String is Immutable

How to create a string

all of the following assignment are equivalent

Assigning string value using single quotes

Str1='hello'

print(str1)

Assigning string value using double quotes

str1="hello"

print(str1)

Assigning string value using trible quotes

str='''hello'''

print(str1)

str="""hello,welcome  to the world of python"""

print(str1)

When you run the program,the output will be:

Hello

Hello

Hello

Hello,welcome to

        the world of python

HOW TO ACCESS CHARACTERS IN A STRING?

str = 'program techie'

print('str = ',str)

 

#print the first character of a string

print('str[0] = ', str[0])

 

#print last character of a string

print('str[-1] = ',str[-1])

 

#print form (slicing) 2nd to 5th character

print('str[1:5] = ', str[1:5])

 

#slicing 6th to 2nd last character

print('str[5:-2] = ',str[5:-2])

 

output

str = program techie

str[0] = p

str[-1] = e

str[1:5] = rogr

str[5:-2] =  am tech

 

# index must be in range

>>>str 1[15]

...

indexError: string index out of range

 

#index  must be an integer

>>>str 1[1.5]

...

typeerror: string indices must be integers

 

HOW TO CHANGE OR DELETE A STRING?

>>> str1 = 'python'

>>> str1[5] = 'a'

...

typeerror: 'str' object does not support item assignment

>>> str1 = 'python'

>>> str1

'python'

 

>>> del str1[1]

...

typeerror: 'str' object doesn't support item deletion

>>> del str1

>>> str 1

...

nameerror: name 'str 1' is not defined

 

 

python string operators

There are many operations that can be performed with string which makes it one of the most used datatypes in python.

concatenation of two or more strings

Joining of two or more strings into a single one is called concatenation.

The + operator does this in python.Simply writing two strings literals together also concatenates them.

 

 The* operator can be used to repeat the string for a given number of times.

str1='python'

str2='world!'

#using string concatenation operator'+'

print('str1+str2=',str1+str2)

 

#using repeative operator'*'

print('str1*3=',str1*3)

 

output

    str1+str2=Python World!

    str1*3=Python Python Python

 

Iterating through string

using for loop we can iterate through a string.Here is an example to count the number of'I'in a string.

 

count=0

for letter in'Python World':

   if(letter=='o'):

        count+=1

print('letter"o"occurs',count,'times')

output

Letter"o"occurs 2 times

 

String Membership Test

          we can test if a sub string exists within a string or not,using the keyword in.

>>>'a' in 'program'

True

>>>'am'not in 'hello'

True

Built-in function to work with python

various built-in function that work with sequences works with string as well.

Some of the commonly used ones are enumerate()and len().The enumerate()function returns an enumerate object.It contains the index and value of all the items in the string as pairs.This can be useful for iteration.

Similarly,len()returns the length(number of characters)of the string.

>>>str1='PYTHON'

>>>enum=list(enumerate(str1))

>>>enum

[(o,'P'),(1,'Y'),(2,'T'),(3,'H'),(4,'O'),(5,'N')]

>>>len(enum)

6

>>>len(str1)

6

>>> 

 

 

#using triple quotes

print('''He asked,"What's Python"''')

#escaping single quotes

print('He asked," What\'s Python?"')

#escaping double quotes

print("He asked,\" What's Python?\"")

 

The format() Method for Formatting Strings

#default(implicit) order

default_order="{},{}and{}".format('hi','hello','how r u')

print('\n---Default order---')

print(default_order)

 

#order using positional arguement

positional_order="{1},{0}and{2}".format('hi','hello','how r u')

print('\n---positional order---')

print(positional_order)

 

#order using keyword arguement

keyword_order="{s},{b}and{j}".format(j='apple',b='orange',s='graphs')

print('\n---keyword order---')

print(keyword_order)

 

          old style formatting

common python string methods

captilize()

syntax

string.captilize()

>>>str="welcome to programtechie"

>>>str.captilize()

Welcome To Programtechie

center

syntax

string.center(width[,fillchar])

parameters

     width ? this is the total width of the string.

     fillchar ? this is the filler character.

for example

>>>str1=" welcome to programtechie "

>>> str1.center(40,"#")

'######### welcome to programtechie #########'

count()

syntax

string.count(substring,starindex=0,endindex=len(string))

for example

>>>str="I am an indian"

>>>str.count("an",0,len(str))

2

>>> 

find()

>>>str="i am an indian"

>>>str.count("an",0,len(str))

2

>>>str.find("an",0,len(str))

5

>>>str.find("am",0,len(str))

2

>>>str.find("um",0,len(str))

-1

Replace()

syntax

following is the syntax for replace()method-

str.replace(old,new[,max])

for example

>>>str="I am an indian"

>>>str.replace("an","us")

'I am us Indius'

isalpha()

>>>string="hai "

>>>string.isalpha()

true

isdigit()

>>>a="1234"

>>>a.isdigit()

true

>>> 

islower()

>>> string=" welcome to programtechie"

>>> string.islower()

True

isnumeric()

>>> a="1234"

>>>a.numeric()

True

isspace()

>>> string="   "

>>> string.isspace()

True

>>> 

istitle()

>>> string=" Welcome To Programtechie "

>>>string.istitle()

True

>>> string2=" WELCOME TO PROGRAMTECHIE "

>>>string2.istitle()

False

>>> 

isupper()

for example

>>>string1="Hai"

>>>string1.upper()

'HAI'

lower()

>>>string1.lower()

'hai'

len(string)

>>>len(string1)

3

>>> 

lstrip() - left strip(removes left space)

rstrip() - Right strip(removes right space)

strip() - removes all space

for example

>>>string="        PROGRAMTECHIE        "

>>>string

'          PROGRAMTECHIE         '

>>>string.lstrip()

' PROGRAMTECHIE             '

>>>string.rstrip()

'                PROGRAMTECHIE'

>>>string.strip()

' PROGRAMTECHIE '

>>> 

upper()

for example

>>>string="I am an indian"

>>>string.upper()

I AM AN INDIAN

swapcase()

>>>str="I am an indian"

>>>str.swapcase()

'i AM AN iNDIAN'

split()

>>>"This will split all words into a list".split()

['This','will'.'split','all','words','into','a','list']

join()

>>>' '.join(['This','will','join','all','words','into','a','string'])

'This will join all words into a string'

>>>'Happy New Year'.find('ew')

7

>>>'Happy New  Year',replace('Happy','Bright')

'Bright New Year'

0 comments:

Post a Comment