Strings

A string is a collection of characters. 

What is a string?

A string in Python is a sequence of characters. The string is immutable.

How to create a string?

Creating a string in python is simple. Strings can be created by placing characters inside a single quote or double-quotes.

The even triple quotes are used for creating multi-line strings and docstrings.

For example

# Creating string using single-quotes

string = 'ashish'

print(type(string))

print(string)

# Creating string using double-quotes

string2 = "ashish"

print(type(string2))

print(string)

# Creating string using triple-quotes

string3= '''This is

            multiple line

            string'''

print(string3)         

string4= """This is

            also

            multiple line

            string"""

print(string4)

 

Output

 

ashish

ashish

This is

multiple line

string

This is

also

multiple line

string

How to create a  string using sequence

The join() function is used for joining the characters and returns the string

sep='' # A seperator between charcaters

_list = ['P', 'y', 't', 'h', 'o', 'n']

string1= sep.join(_list)

print(string1)

_tuple = ('P', 'y', 't', 'h', 'o', 'n')

string2= sep.join(_tuple)

print(string2)

 

Output

Python

Python

 

Note To convert the list or tuple to a string, all the elements must be characters.

How to access element(s) from a string?

There are two ways to access the character(s)  from the string

  1. Using Index operator
    1. Index
    2. Negative Index
  2. Using Slicing

Using Index

The index operator []  is used to access an element from a string.

The index or indices start from 0, the first element  can be retrieved using index o, for example string[0]

A string with 6 characters will have  indexes from 0 to 5 for example

 

string ='Python'

The string is

 

Index

0

1

2

3

4

5

Element

'P'

'y'

't'

'h'

'o'

'n'

 

Note:

The valid index range for  a string  is  0 to len(string) - 1, 0 to the length of the string- 1

 Accessing indexes other than these ( 0 to the length of the string -1) will raise an IndexError.

The index must be an integer. Using other than an integer as an index will result in a TypeError

string = 'Python'

print(string[0])

print(string[5])

print(string[6])

print(list['a'])

Output

P

n

Traceback (most recent call last):

  File "test.py", line 117, in

    print(string[6])

IndexError: string index out of range

 

Traceback (most recent call last):

  File "test.py", line 120, in

    print(_list['a'])

TypeError: string indices must be integers

 

Negative indexing

Python allows negative indexing to access elements from sequences. The index  -1 refers to the last element of the list.

 

Index

0

1

2

3

4

5

Element

'P'

'y'

't'

'h'

'o'

'n'

Negative Index

-6

-5

-4

-3

-2

-1

 

Example using Negative Index

string = 'Python'

print(string[-1])

print(string[-6])

Output

n

P

 

Slicing

Slicing is used to select  a range of  character(s) from  the string using colon ( : ) operator for example

Example: 1

string[2:5]

                                                   

Index

0

1

2

3

4

5

Element

'P'

'y'

't'

'h'

'o'

'n'

Negative Index

-6

-5

-4

-3

-2

-1

 

Output

tho

 

Example: 2

string[1:]  # slicing a string from index 1 to end of the string

 

                                     

Index

0

1

2

3

4

5

Element

'P'

'y'

't'

'h'

'o'

'n'

Negative Index

-6

-5

-4

-3

-2

-1

 

Output

ython

 

Example: 3

string[-1: -5# slicing string from index 1 to end of the list

Index

0

1

2

3

4

5

Element

'P'

'y'

't'

'h'

'o'

'n'

Negative Index

-6

-5

-4

-3

-2

-1

                                          

Output

ython

 

Example: 4

_list[4:# slicing list from index 4 to the end of the list

                                                                        ​​​​​​​

Index

0

1

2

3

4

5

Element

'P'

'y'

't'

'h'

'o'

'n'

Negative Index

-6

-5

-4

-3

-2

-1

 

Output

on

Example: 5

string[:-4# slicing string from index -6 to -5

Index

0

1

2

3

4

5

Element

'P'

'y'

't'

'h'

'o'

'n'

Negative Index

-6

-5

-4

-3

-2

-1

                             

Output

Py

 

Example: 6

_list[:# all the elements from the string

                            

Index

0

1

2

3

4

5

Element

'P'

'y'

't'

'h'

'o'

'n'

Negative Index

-6

-5

-4

-3

-2

-1

Output

Python

 

Example: 7 using step parameter  with slicing

string = 'Python'

print(string[0:7:2])

                

Index

0

1

2

3

4

5

6

7

Element

'P'

'y'

't'

'h'

'o'

'n'

'i'

's'

Negative Index

-8

-7

-6

-5

-4

-3

-2

-1

Output

Ptoi

Example 8

string = 'Pythonis'

print(string[1::2])

                                            

Index

0

1

2

3

4

5

6

7

Element

'P'

'y'

't'

'h'

'o'

'n'

'i'

's'

Negative Index

-8

-7

-6

-5

-4

-3

-2

-1

Output

yhns

 

Example 9

string = 'Pythonis'

print(string[::3])

                                                                                                   

Index

0

1

2

3

4

5

6

7

Element

'P'

'y'

't'

'h'

'o'

'n'

'i'

's'

Negative Index

-8

-7

-6

-5

-4

-3

-2

-1

Output

Phi

How to modify the character(s) from a string

A String is immutable, once a  string is created it cannot be changed, try changing its element result in an error

Example 1

string = 'python'

string[0]= 'P'

Output

TypeError: 'str' object does not support item assignment

 

How to add characters(s) to a string

The  + concatenation operator is used to add character(s)

Example:1 

string = 'python'

print( string + ' is fun!!!')

print( string )

Output

python is fun!!!

python

Note:  String is immutable , the + operator concatenation the string and return a new string , the original string is not changed.

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

Example:1 

string = 'p'

print( string  * 3)

Output

ppp

How to delete or remove elements from a list?

String are immutable trying to delete a character result into error

Example: 1

string = 'Python'

del string[0]

Output

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

 

String Membership Test

The in  and  not in keyword is used to find the  existence  of a character  in the string

string = 'Python'

print('P' in  string)

print('p' in  string)

print('P' not in  string)

print('p' not in  string)

 

Output

True

False

False

True

Iterating through a string

You can iterate the list using 'for' loop since the list is  iterable object

Example: 1  Iterating string with for loop

string = 'Python'

for char in string:

            print(char)

Output

P

y

t

h

o

n

 

Example: 2  Iterating string with  while loop

counter=0

length = len(string)

while(counter < length):

          print(string[counter])

            counter += 1

Output

P

y

t

h

o

n

 

Searching characters in  a string

You can find the character or substring using find() and rfind() function,

Example: 1 

searchchar= input("Enter search string: ")

string ='Python'

if ( string.find(searchchar) > 0):

            print(searchchar, " found in " , string)

else:

          print(searchchar, " not found in " , string)

Output

Enter search string: n

n  found in  Python

Enter search string: m

m  not found in  Python

 

Example: 2 

searchchar= input("Enter search string: ")

string ='testing'

loc = string.rfind(searchchar)

if ( loc > 0):

           print(searchchar, " found in " , string, "\

          at location ", loc+1)

else:

             print(searchchar, " not found in " , string)

Output

Enter search string: t

t found in  testing  at location  4

​​​​​​​Enter search string: p

p  not found in  testing