top of page

Python: Working with Strings

  • 'str' is most commonly used data type.

  • In python there is no 'char' data type.

  • ch=’a’ is treated as str type only not char type.

  • We can create string object using ‘ ‘ or ‘’ ‘’

Example

s=’knowcubs’

or

s=”knowcubs”

String Data Type Python

Multi line string literals :

If we need to write multi line string literals we can use Triple quotes (triple single quotes or triple double quotes).

 

Example

Multiline line string literals
SDT2.png
String Data Type Python

Single quotes as a symbol

There are 2 ways to use single quotes as a symbol

1. use double quotes to represent string.

String Data Type Python

2. use \(backslash symbol)

String Data Type Python

Double quotes as a symbol

There are 2 ways to use double quotes as a symbol

1. use single quotes to represent string.

String Data Type Python

2. use \(backslash symbol)

String Data Type Python

How to access characters of the string

1. By using index

In python 2 types of index are possible means we can access a string from both side left to right and right to left.

i) +ve index(from left to right)

ii) -ve index(from right to left)

How to access characters of the string
String Data Type Python

i) +ve index(from left to right)

String Data Type Python

ii) -ve index(from right to left)

String Data Type Python

If we try to access out of range Index.

String Data Type Python

#Write a program to accept some string and print all character with index.

String Data Type Python
String Data Type Python

2. By using slice operator

Slice Operator is used to divide string into smaller substrings

Form:1 S[begin:end] - returns substring from begin index to end-1 index.

Example

s=’knowcubs’

s[1:7]==>nowcub

s[2:7]==>owcub

​Note 1: End index is not mandatory, if you are not specifying end by default end value  is end of the string.

s[1:]==>nowcubs

String Data Type Python

Note 2: begin index is also not mandatory, if you are not specifying begin by default begin value  is start of the string.

s[:7]==>knowcub

String Data Type Python

Note3: begin and end both are not mandatory to specify.

String Data Type Python

Form:2  S[begin:end:step]

By default value of step is 1. Step value can be either +ve or -ve

If +ve then it will be forward direction (left to right)

If -ve then it will be backward direction (right to left)

If +ve  forward direction from begin to end-1

If -ve  backward direction from begin to end+1

Example

s=’0123456789’

String Data Type Python

S[2:8:1] =>234567

S[2:8:-1] =>empty output

S[2:8:0] =>slice step value cannot be 0

S[-1:-6:-1]=>98765

S[2:-5:1]=>234

S[1:6:-2]=>empty string

S[0:-5:-5]=>empty    

 

#Reverse a string using slice operator

String Data Type Python
String Data Type Python

Mathematical Operation on string object

1. + (Concatenation Operator )

Mathematical operation on string object
String Data Type Python

2.*(Repetition Operator )

String Data Type Python

Note: For repetition operator first  argument must be string and second argument must be int otherwise you will get syntax  error.

 

Inbuilt functions in string

len(): it  is  use to find no of  characters present in a list.

Example

Inbuilt functions
String Data Type Python

# WAP to access each character of string in forward direction and backward direction

1. By using slice operator

String Data Type Python
String Data Type Python

2. By using while loop

String Data Type Python
String Data Type Python

Membership operators in string

in

not in

 

Example

s=”knowcubs”

print(‘c’ in s)#True

print(‘z’ in s)#False

#WAP to check substring is available in string or not

Membership operators
String Data Type Python
String Data Type Python

Comparison operators in string

>, >=, <, <=

Comparison takes place based  on dictionary  order.

Equality operators

==, !=

In general '==' operator meant for content operator

Example

Comparison operators
String Data Type Python
String Data Type Python

Methods to remove spaces

lstrip()

to remove spaces present at left side or beginning of the  string.

rstrip()

to remove spaces present at right side or end of the  string.

strip()

strip is used to remove spaces from beginning and end both side.

Example

Methods to remove spaces
String Data Type Python
String Data Type Python

Finding substring

To find whether or not a substring is present in string, following operators are used:

  • find()

  • rfind()

  • index()

  • rindex()

 

1. find()

find(substring): find substring from beginning  of the string.

If the substring is available  then find() method  returns index of first occurrence of  the substring otherwise it returns -1.

rfind(substring): find substring from backside (right side) of the string.

If the substring is available  then rfind() method  returns index of first occurrence from right side of  the substring otherise it retruns -1.

Example

Finding substring
String Data Type Python
String Data Type Python

find(substring,begin,end): Find substring from beginning to end-1 of the string. By default begin value is 0 and end value is length-1.

rfind(substring,begin,end): Find substring from end  of the string. By default begin value is 0 and end value is length-1.

String Data Type Python
String Data Type Python

2. index()

same as find() method  except that  if the specified substring is not available you will get value error not –1.

String Data Type Python
String Data Type Python

rindex()

same as rfind() method  except that  if the specified  substring is not available we will get value error not –1.

String Data Type Python
String Data Type Python

Counting substrings in the given string

count(substring): used to find number of times the specified substring is present in the given string.

count(substring,begin,end): similar to count() but in this we can specify begin and end index also. By default begin value  is 0 and end value is length-1.

Example

Counting substrings in the given string
String Data Type Python
String Data Type Python

Replacing a string with another string

replace(oldstring,newstring): replace a string with specified string.

Example

Replacing a string with another string
String Data Type Python
String Data Type Python

When we use replace() method it does not affect the existing object, instead it creates new object.

Example

String Data Type Python
String Data Type Python

Splitting of string

split(): used to split a string into parts based on separator.

Default separator is space (‘ ’). Splited string will be stored in a list.

Example

Splitting of strings
String Data Type Python
String Data Type Python

#Split a date string based on separator ‘-’

String Data Type Python
String Data Type Python

rsplit(): It gives in split reverse direction (from right).

Example: If we want maximum 4 substrings from right.

String Data Type Python
String Data Type Python

Joining of strings

Join(): it joins each element of list by a string separator and returns the concated string.

Example

Joining of strings
String Data Type Python
String Data Type Python

Changing case of a string

upper(): To convert to upper case

lower(): To convert to lower case

swapcase(): To convert lower to upper and upper to lower

title(): Every word start with upper case.

capitalize(): In the total string first character is upper case and other one is lower case.

 

Example

Changing case of a string
String Data Type Python
String Data Type Python

Checking Starting and Ending part of the String

startswith(substring)

endswith(substring)

Example

Checking Starting and Ending part of the String
String Data Type Python
String Data Type Python

 #To print characters at odd position and even position for the given string.

1st method:

String Data Type Python
String Data Type Python

2nd method

String Data Type Python
String Data Type Python

Check type of characters present in a string

isalnum(): to check characters are alphanumeric or not {A-Z ,a-z,0-9}

isalpha():to check characters are alphabetic or not {A-Z,a-z}

isdigit(): to check characters are digit or not {0-9}

islower(): to check characters are lowercase or not.

isupper(): to check characters are in upper case or not.

istitle(): to check characters are in title case or not

isspace(): to check character is space or not.

Example

print(‘knowcubs786’.isalnum() #True

print(‘knowcubs786’.isalpha() #False

print(‘knowcubs’.isalpha() #True

print(‘knowcubs’.islower() #True

print(‘knowcubs’.isupper() #False

print(‘Indian Space Research Organisation’.istitle() #True

print(‘Indian Space Research Organisation’.isspace() #True

#WAP to separate alphabets and digits

Check type of characters present in a string
String Data Type Python
String Data Type Python

#Input: a4b3c2 Output: aaaabbbcc

String Data Type Python
String Data Type Python

#Input: a4k3b2 Output: aeknbd

String Data Type Python
String Data Type Python

#WAP to reverse string

1st  method:

String Data Type Python
String Data Type Python

2nd method:

String Data Type Python
String Data Type Python

3rd method:

String Data Type Python
String Data Type Python

#WAP to reverse internal content of each word of a  string.

String Data Type Python
String Data Type Python
String Data Type Python
bottom of page