STRING Data Type in Python

STRING Data Type in Python

In STRING Data Type in Python are arrays of bytes representing Unicode characters. A string is a collection of one or more characters put in a single quote, double-quote or triple quote. In python there is no character data type, a character is a string of length one. It is represented by str class.

Strings are sequences of character data. The string type in Python is called str.

String literals may be delimited using either single or double quotes. All the characters between the opening delimiter and matching closing delimiter are part of the string:

str represents String data type. A String is a sequence of characters enclosed within single quotes or double quotes.

s1=’Cloud’

s1=”Cloud”

 

Slicing of Strings:

1) slice means a piece

2) [ ] operator is called slice operator, which can be used to retrieve parts of String.

3) In Python Strings follows zero based index.

4) The index can be either +ve or -ve.

5) +ve index means forward direction from Left to Right

6) -ve index means backward direction from Right to Left

 

-5   -4 -3  -2    -1

C L O U D

0      1    2     3      4

S[0] à C

S[-5] àC

S[-6] à IndexError: string index out of range

How to define multi-line String Literals?

We can define multi-line String literals by using triple single or double quotes.

Eg:

>>> s = ”’The

Multi-line

Example ”’

>>>The

Multi-line

Example

We can also use triple quotes to use single quotes or double quotes as symbol inside String literal.

s = ‘This is ‘ single quote symbol’ à Invalid

s = ‘This is \’ single quote symbol’ à Valid

s = “This is ‘ single quote symbol” à Valid

s = ‘This is ” double quotes symbol’ à Valid

 

How to Access Characters of a String?

We can access characters of a string by using the following ways.

1) By using index

2) By using slice operator

1) Accessing Characters By using Index:

Python supports both +ve and -ve Index.

+ve Index means Left to Right (Forward Direction)

-ve Index means Right to Left (Backward Direction)

>>> S=’PYTHON’

>>>S[0]

‘P’

>>>S[4]

‘O’

>>>S[10]

IndexError: string index out of range

If we are trying to access characters of a string with out of range index then we will get error saying: IndexError

2) Accessing Characters by using Slice Operator:

Syntax: s[bEginindex:endindex:step]

Begin Index: From where we have to consider slice (substring)

End Index: We have to terminate the slice (substring) at endindex-1

Step: Incremented Value.

 

If we are not specifying begin index then it will consider from beginning of the string.

If we are not specifying end index then it will consider up to end of the string.

The default value for step is 1.

1) >>> s=”Learning Python is very very easy!!!”

2) >>> s[1:7:1]

3) ‘earnin’

4) >>> s[1:7]

5) ‘earnin’

6) >>> s[1:7:2]

7) ‘eri’

8) >>> s[:7]

9) ‘Learnin’

10) >>> s[7:]

11) ‘g Python is very very easy!!!’

12) >>> s[::]

13) ‘Learning Python is very very easy!!!’

14) >>> s[:]

15) ‘Learning Python is very very easy!!!’

16) >>> s[::-1]

17) ‘!!!ysae yrev yrev si nohtyP gninraeL’

 

Behaviour of Slice Operator:

1) s[bEgin:end:step]

2) Step value can be either +ve or –ve

3) If +ve then it should be forward direction(left to right) and we have to consider bEgin to end-1

4) If -ve then it should be backward direction (right to left) and we have to consider bEgin to end+1.

 

***Note:

In the backward direction if end value is -1 then result is always empty.

In the forward direction if end value is 0 then result is always empty.

In Forward Direction:

default value for bEgin: 0

default value for end: length of string

default value for step: +1

In Backward Direction:

default value for bEgin: -1

default value for end: -(length of string+1)

len() in-built Function:

We can use len() function to find the number of characters present in the string.

Eg:

s = ‘cloud’

print(len(s)) à 5

Checking Membership:

We can check whether the character or string is the member of another string or not by using in and not in operators

s = ‘Cloud’

print(‘d’ in s) à True

print(‘z’ in s) à False

Removing Spaces from the String:

We can use the following 3 methods

1) rstrip() à To remove spaces at right hand side

2) lstrip() àTo remove spaces at left hand side

3) strip() à To remove spaces both sides

1) city=input(“Enter your city Name:”)

2) scity=city.strip()

3) if scity==’Hyderabad’:

4) print(“Hello Hyderbadi..SHYAM”)

5) elif scity==’Chennai’:

6) print(“Hello Madrasi…RAM”)

7) elif scity==”Bangalore”:

8) print(“Hello Kannadiga…RAVI”)

9) else:

10) print(“your entered city is invalid”)

 

Other String Functions:

Changing Case of a String:

We can change case of a string by using the following 5 methods.

1) upper() à To convert all characters to upper case

2) lower() à To convert all characters to lower case

3) swapcase() à Converts all lower case characters to upper case and all upper case characters to lower case

4) title() à To convert all character to title case. i.e first character in every word should be upper case and all remaining characters should be in lower case.

5) capitalize() à Only first character will be converted to upper case and all remaining characters can be converted to lower case

1) s = ‘learning Python is very Easy’

2) print(s.upper())

3) print(s.lower())

4) print(s.swapcase())

5) print(s.title())

6) print(s.capitalize())

Output:

LEARNING PYTHON IS VERY EASY

learning python is very easy

LEARNING pYTHON IS VERY eASY

Learning Python Is Very Easy

Learning python is very easy

 

Checking Starting and Ending Part of the String:

Python contains the following methods for this purpose

1) s.startswith(substring)

2) s.endswith(substring)

 

s = ‘learning Python is very easy’

print(s.startswith(‘learning’))

print(s.endswith(‘learning’))

print(s.endswith(‘easy’))

Output:

True

False

True

 

To Check Type of Characters Present in a String:

Python contains the following methods for this purpose.

1) isalnum(): Returns True if all characters are alphanumeric( a to z , A to Z ,0 to9 )

2) isalpha(): Returns True if all characters are only alphabet symbols(a to z,A to Z)

3) isdigit(): Returns True if all characters are digits only( 0 to 9)

4) islower(): Returns True if all characters are lower case alphabet symbols

5) isupper(): Returns True if all characters are upper case aplhabet symbols

6) istitle(): Returns True if string is in title case

7) isspace(): Returns True if string contains only spaces

 

This is about STRING Data Type in Python and its functions.

Related Posts:

Python Tutorial – Learn Python

What is Python? What makes Python so Powerful?

Variables in Python – Constant, Global & Static Variables

Namespacing and Scopes in Python

Operators in Python

Data Types in Python

LIST Data Structure in PYTHON

TUPLE Data Structure in PYTHON

Differences between List and Tuple

SET Data Structure in PYTHON

DICTIONARY Data Structure in PYTHON

Database Programming in Python

What is Multithreading in Python?

Python Exception Handling Using try, except and finally statement

File Handling in Python

Python Random module

Python reduce() Function

Python map() Function

Python filter() Function

Lambda Function in PYTHON (Anonymous Function)

Python Interview Question And Answers