Python String | Class 11 | Class 12 | CBSE | Computer Science | Informatics Practices | Notes | Study Material | Python Revision Tour

 Chapter 10:Strings Manipulation

Introduction

Immutable

A strings are enclosed with ‘ ’,” ”,’’’  ‘’’

A string Object always represents the same string.‘123’,

Python strings are stored in memory by storing individual character in contiguous memory

This sequences of UNICODE character may include a letter,a number,special character,white-space or a backslash

For example:

“Hello Python”

‘Hello Python’

‘’’ Hi Hello Python1234’’’




Creating a string:

A=”Good Morning”

>>>X=”Write article on \”AI\” briefly”

‘Write article on ”AI” briefly’

Empty String

>>>str=”  ”

>>>str

‘ ’

>>>str=’ ’

>>>str

‘ ’

 

Multi-line  String:

>>>A=’’’ This is a \

Multi-line String \

Example’’’

>>>A

This is a Multi-line String Example

 

Traversing String

Accessing all the elements of the string one after the other by using the subscript or index value.

For example:

S=”HELLO PYTHON”

Positive Index (Forward Index)

0

1

2

3

4

5

6

7

8

9

10

11

(String Variable) S=

H

E

L

L

O

 

P

Y

T

H

O

N

Negative Index (Backward index)

-12

-11

-10

-9

-8

-7

-6

-5

-4

-3

-2

-1

 

 

>>>S="HELLO PYTHON"

>>>S[0]

'H'

>>>S[3]

'L'

>>>S[-1]

'N'

>>>S[-4]

'T'

 

Special String Operator

1. Slicing              -->  String[range]

2. Concatenation   --> String1 + String2

3. Repetition         -->  String1*x

4. Membership     -->in,not in

5. Reverse          --> String [::-1]

6. Comparison

1. Slicing

range(start,stop,step)

(start:stop:step)

 stop=stop-1

For Example:

>>>str=”HELLO PYTHON”

>>> str[1:5]

'ELLO'

>>> str[0:8]

'HELLO PY'

>>> str[1:9:-1]

''

>>>


2. Concatenation (+)

Joining the two elements

For Example:

>>> str="GOOD"

>>> str1="Morning"

>>> str+str1

'GOODMorning'

>>> str1="   Morning"

>>> str+str1

'GOOD   Morning'

ERROR: TYPE ERROR

>>> "good"+1

Traceback (most recent call last):

  File "<pyshell#0>", line 1, in <module>

    "good"+1

TypeError: can only concatenate str (not "int") to str

3. Repetition:(*)

For Example:

>>> str="Hi !!!   "

>>> str*3

'Hi !!!   Hi !!!   Hi !!!   '

>>> 5*"A@B "

'A@B A@B A@B A@B A@B '

>>>5*"A#B"

'A#BA#BA#BA#BA#B'

CAUTION!

For example

2*3=6   #Multiplication

“2”*3=”222” #Replication

 TYPE ERROR: / INVALID

"2"*"3"

Traceback (most recent call last):

  File "<pyshell#4>", line 1, in <module>

    "2"*"3"

TypeError: can't multiply sequence by non-int of type 'str'

 

4. Membership

There are two membership operators for strings.These are in and not in.

in Return True  if a character or a substring exits in the given strings;False otherwise

Not in Return True if a character or a substring does not exits in the given string;False otherwise

For example:

>>> str="HELLO PYTHON"

>>> 'LLO' in str

True

>>> 'aa' in str

False

>>> 'zz' in str

False

>>> 'abc' not in str

True

>>> 'py' not in str

True

>>> 'Py' not in str

True

>>>

5. Reverse

For Example:

>>> str="HELLO PYTHON"

>>> str[::-1]

'NOHTYP OLLEH'

>>>

6. Comparison Operator

Standard comparison operator i.e, (<,>,<=,>=,==,!=)

For example

>>>"a"=="a"

True

>>>"abc"=="abc"

True

>>>"a"!="abc"

True

>>>"A"!="a"

True

>>>"a"<"A"

False

>>>"a">"A"

True

>>>"a">="ab"

False

>>>"0">"2"

False

>>>"3">="4"

False

>>>"3"=="3"

True

 

Strings Methods and Build-in Function

1. len() -- This method returns the length of the string

Syntax:

len(str)

For example:

>>> a="PYTHON"

>>> len(a)

6

>>>

2. Capitalize() -- This method returns the exact copy of the string with the first letter in uppercase

>>> a=”python”

>>>a.capitalize()

Python

>>> a="python programming language"

>>> a.capitalize()

'Python programming language'

>>> x="Welcome"

>>> x.capitalize()

'Welcome'

>>>

3. isalpha() - This function checks for

Alphabets in an inputted string.it returns True if the string contains only letters, otherwise returns False:

Syntax

<string>.isalpha()

>>> str="Good"

>>>str.isalpha()

True

>>> str="123good"

>>> str.isalpha()

False

4. isalnum() - The isalnum() method returns True if all the characters are alphanumeric,meaning alphabet numbers(a-z) numeric (0-9)

Note: Example of characters that are not alphanumeric (space) ,@,#,$,%

Syntax:

str.isalnum()

>>> str="Good"

>>> str.isalnum()

True

>>> str="123Good"

>>> str.isalnum()

True

>>> str="1234"

>>> str.isalnum()

True

>>> str="Good Morning"

>>> str.isalnum()

False

>>> str="abc@gmail.com"

>>> str.isalnum()

False

>>>

5. isdigit() - This function returns True if the string contains only digits, otherwise False

Syntax:

str.isdigit()

>>> str="Good"

>>> str.isdigit()

False

>>> str="12345"

>>> str.isdigit()

True

>>> str="123Good"

>>> str.isdigit()

False

>>> str="2@abc"

>>> str.isdigit()

False

>>>

6. title()- This function returns the string with first letter of every word in the string uppercase and rest in lowercase.

Syntax:

str.title()

For example:

>>> str="hello ITS all about STRINGS"

>>> str.title()

'Hello Its All About Strings'

>>>

7.istitle() --The istitle() function doesn`t take any arguments it returns True if the string is properly “titlecased”

Else returns False if the string is not a “titlecase” string or an empty string.

Python Programming Fundamental ---> Title

Syntax:

str.istitle()

For Example:

>>> str="All Learn python"

>>> print(str.istitle())

False

>>> str="All Learn Python"

>>> print(str.istitle())

True

>>> str="PYTHON"

>>> print(str.istitle())

False

>>> str="python"

>>> print(str.istitle())

False

>>> str="python   "

>>> print(str.istitle())

False

>>> str="python@prongram"

>>> print(str.istitle())

False

>>>

 

8.isspace()--This function returns True if the string contains only whitespace characters otherwise returns False.

Syntax:

str.isspace()

For Example:

>>> str="Hello ITS all about STRINGS"

>>> print(str.isspace())

False

>>> str="    Hello ITS all about STRINGS"

>>> print(str.isspace())

False

>>> str="   "

>>> print(str.isspace())

True

>>>

9.count() - This  function returns number of times substring  occurs in the given string if we do not give start index and end index then searching starts from index 0 and ends at length of the string.

Syntax:

str.count(“substring”,start,end)

For example:

>>> str="Hello Hi Python Hello World Hi Welcome"

>>> str.count("Hello",12,40)

1

>>> str.count("Hi",2,40)

2

>>> 

10.lower() -This function converts all the uppercase letters in the string into lowercase.

Syntax:

>>> str="Learning Python"

>>> print(str.lower())

learning python

>>> str="PYthON"

>>> print(str.lower())

python

>>>

 

11.islower() - This function returns True If all the letter in the string are in lowercase.

Syntax:

str.islower()

For example:

>>> str="Learning Python"

>>> print(str.islower())

False

>>> str="python"

>>> print(str.islower())

True

>>>

12.upper() - This function converts lowercase letters in the string into uppercase.

Syntax:

str.upper()

For Example:

>>> print(str.upper())

LEARNING PYTHON

>>> str="python"

>>> print(str.upper())

PYTHON

>>> str="PYthON"

>>> print(str.upper())

PYTHON

>>>

13.isupper() - This function returns True If the string is in Uppercase

Syntax:

str.isupper()

For Example:

>>> str="Learning Python"

>>> print(str.isupper())

False

>>> str="PYTHOn"

>>> print(str.isupper())

False

>>> str="PYTHON"

>>> print(str.isupper())

True

>>> 

14.lstrip() -- This function returns the string after removing the spaces from the left of the string

Syntax:

str.lstrip()

Or

str.lstrip(chars)

 For Example:

>>> str="    Green REvolution"

>>> print(str.lstrip())

‘Green REvolution’

>>> print(str.lstrip("Gr"))

    Green REvolution

>>> str="Green REvolution"

>>> print(str.lstrip("Gr"))

een REvolution

>>> str="Green REvolution    "

>>> print(str.lstrip("Gr"))

een REvolution    

>>> str="    Green REvolution     "

>>> print(str.lstrip("Gr"))

    Green REvolution     

>>>

15.rstrip()---  this function remove all the trailing whitespaces from the right of the string

Syntax:

rstrip()

Or

rstrip(chars)

>>>

For Example:

>>> str="Green Revolution    "

>>> print(str.rstrip())

‘Green Revolution’

>>> str="    Green Revolution    "

>>> print(str.rstrip())

    ‘ Green Revolution’

>>> str="Green Revolution    "

>>> print(str.rstrip("Gr"))

Green Revolution    

>>> str="Green Revolution    "

>>> print(str.rstrip("tion"))

Green Revolution    

>>> str="Green Revolution"

>>> print(str.rstrip("tion"))

Green Revolu

>>>

16.strip() -- This function returns the string the spaces both on the left and right of the string

Syntax:

str.strip()

 For Example:

>>> str="   Hello ITS all about STRINGS     "

>>> print(str.strip())

‘Hello ITS all about STRINGS’

>>> str="   Hello ITS all about STRINGS"

>>> print(str.strip())

Hello ITS all about STRINGS

>>> str="Hello ITS all about STRINGS     "

>>> print(str.strip())

Hello ITS all about STRINGS

>>>

17.Split()-- The split() method breaks up a string at the specified separator and returns a list of substring

Syntax:

str.split([separator[,maxsplit]])

Separator #optional

The string splits at the specified separator,If the specified,any white-space (space,newline)

Maxsplit #Optional

This maxsplit defines the maximum number of splits.

The default values of maxsplit is -1,which means no limit on the number of splits

For example:

>>>x=”Red$blue$green”

>>>x.split(“$”)

[“Red”,”blue”,”green”]

>>> g="red:blue:orange:pink"

>>> print(g.split(':',2))

['red', 'blue', 'orange:pink']

>>> print(g.split(':',1))

['red', 'blue:orange:pink']

>>> print(g.split(':',5))

['red', 'blue', 'orange', 'pink']

>>> print(g.split(':',0))

['red:blue:orange:pink']

>>>

18.replace() - This function replaces all the occurrences of the old string with the new string

Syntax:

variable.replace(old,new)

For example

>>> x="This is a String Example"

>>> x.replace("is","was")

'Thwas was a String Example'

>>>

19.Find()- This function  is used to search the first occurrence of the substring in the gives string. The find() method returns the lowest index of the substring if it is found in the given string.If substring is not found,it returns -1 its syntax is

str.find(sub,start,end)

>>> str="Green Revolution"

>>> str.find("green")

-1

>>> str.find("Green")

0

>>> str.find("een")

2

>>> str="Green Revolution"

>>> str.find("G")

0

>>> str.find("R")

6

>>> str.find("e")

2

>>> str.find("n")

4

>>> str.find("n",3,20)

4

>>> str.find("n",5,20)

15

>>>

20.index() - This function is quite similar to find() but raise an exception if the substring is not present in the given string.

Syntax:

index(substring,start,end)

    >>>str=”Hello ITS all about STRINGS!!!”

    >>>str.index(‘Hello’)

    0

    >>> str.index("Hel")

    0

    >>> str.index("ll")

    2

    >>> str.index("all")

    10

    >>> str.index("t",5,30)

    18

    >>> str.index("T",5,30)

    7    

    >>>S[0]=’H’

    >>>Str.index(“H”)

0

VALUE ERROR

>>> str.index("hi")

Traceback (most recent call last):

  File "<pyshell#18>", line 1, in <module>

    str.index("hi")

ValueError: substring not found

>>> str.index("h",5,30)

Traceback (most recent call last):

  File "<pyshell#19>", line 1, in <module>

    str.index("h",5,30)

ValueError: substring not found

 

21.join(Sequence)--This function returns a string in which the string elements have been joined  by a string separator.

Sequences: join() takes an argument which is of sequence data type, capable of returning its element one at a time.

This method returns a string which is the concatenation of each element of the string and the string separator between each elements of the string

Syntax:

str.join(sequences)

For example:

>>> str="12345"

>>> s='-'

>>> s.join(str)

'1-2-3-4-5'

>>> s='*'

>>> s.join(str)

'1*2*3*4*5'

>>> s='****'

>>> s.join(str)

'1****2****3****4****5'

>>>

22.swapcase() -- This function converts and returns all uppercase characters into lowercase character and vice versa of the given string.It does not take any argument.

Syntax:

str.swapcase()

For Example:

>>> str="Welcome"

>>> str.swapcase()

'wELCOME'

>>> str="PYTHon"

>>> str.swapcase()

'pythON'

>>> str="PYTHON"

>>> str.swapcase()

'python'

>>> str="python"

>>> str.swapcase()

'PYTHON'

>>> str="python  "

>>> str.swapcase()

'PYTHON  '

>>> str="python@"

>>> str.swapcase()

'PYTHON@'

>>>

23.partition(Separator)-Partition function is used to split the given string using the specified separator and returns a tuple with three parts.

 Syntax:

str.partition(Separator) 

For example:

>>> str="xyz@gmail.com"

>>> str.partition("@")

('xyz', '@', 'gmail.com')

>>> str.partition(".")

('xyz@gmail', '.', 'com')

>>> str.partition("g")

('xyz@', 'g', 'mail.com')

>>>

Other Functions

1. ord()

This function returns the ASCII/Unicode of the character.

Syntax:

ord()

For example

>>>ch=’A’

>>>ord(ch)

65

2. chr()

This Function returns the character represented by the inputted Unicode /ASCII number.

>>> chr(97)

'a'

>>> chr(65)

'A'

>>>

 Download PDF

Post a Comment

0 Comments