string in python

String in Python – Examples and Operations


Similar to other programming languages, Python also has a string data type. The string is a class that comes with various useful operations. In this tutorial, we will learn the declaration of strings and various operations with examples.

How to declare the string?

In python, a string can be declared using single, double or triple quotes. Generally, we avoid triple quotes, most uses for the multiline strings. Following are a few declaration examples.

str = "Hello , i am a string";
 print(str);
 str = 'Hello , String with single quotes';
 print(str);
 str = """String with triple quotes"""
 print(str);

Output->

str = "Hello , i am a string";
 print(str);
 str = 'Hello , String with single quotes';
 print(str);
 str = """String with triple quotes"""
 print(str);

You can break a string into multiple lines when using triple quotes. With others, Python will throw an error while execution.

str = "Hello , 
     i am a string";
 print(str);

Output->

py Strings.py
   File "Strings.py", line 1
     str = "Hello ,
                   ^
 SyntaxError: EOL while scanning string literal
str = """String with 
                 triple quotes"""
 print(str);

Output->

str = """String with 
                 triple quotes"""
 print(str);

Accessing individual characters in a string-

Being an array of characters, we can access each element of the string. But we can not modify (strings are immutable) a character in the declared string as we can do with an array.

print elements->

str = """String with 
                 triple quotes"""
 print("Ele -> 1", str[1]);
 print("Ele -> 1", str[4]);

Output->

Ele -> 1 t
 Ele -> 1 n

Modify an element->

str = """String with 
                 triple quotes"""
 str[4] = 'g';

Output->

Traceback (most recent call last):
   File "Strings.py", line 5, in 
     str[4] = 'g';
 TypeError: 'str' object does not support item assignment

Few more substring/element operations –

str = "I am a string";
 last element in string
 print(str[-1]);
 get substring between 2 to 6 from start
 print(str[2:6]);
 get substring between 1st from start and 2nd from last
 print(str[1:-2]);

Output->

g
 am a
  am a stri

Errors while accessing a string-

Python has strict error checking while handling strings. A programmer may induce unintentional errors. E.g index outside the range, wrong formats etc. While executing, if any error case occurs, python prints the errors. In the following code, we will show a few cases.

str = "I am a string";
 out of range
 print(str[-100]);

File "Strings.py", line 4, in 
     print(str[-100]);
 IndexError: string index out of range

 print(str[2,6]);

File "Strings.py", line 4, in 
     print(str[-100]);
 IndexError: string index out of range