My Blog
Articles related to programming, computer science, technology and research.

19/04/2018 Categories: Python Programming. No Comments on Strings in Python Programming

Contents1 Introduction to Strings in Python2 Sequence Operations on Strings3 String Immutability4 String Specific Methods Introduction to Strings in Python   A string is a sequence of one character strings. Strings are used to store textual information. Examples of strings:   ‘Python’ ‘Ramesh Kumar’ “A” “123”   Sequence Operations on Strings   We can find […]

Introduction to Strings in Python

 

A string is a sequence of one character strings. Strings are used to store textual information. Examples of strings:

 

 

Sequence Operations on Strings

 

We can find the length (number of characters) of a string using the pre-defined function len:

 

 

We can also fetch individual characters from the strings using indexing. The index of first character starts from 0, next is 1, and so on:

 

 

Negative indexes are used to index from right to left in a string:

 

 

Sequences like strings also support another form of indexing called slicing which is used to extract a part of the string:

 

 

More examples on slicing:

 

 

Strings can be concatenated using the ‘+’ operators as shown below:

 

 

A string can be printed multiple times by using the power (**) operator as shown below:

 

 

String Immutability

 

In Python, every object can be classified as mutable or immutable. Numbers, strings, and tuples are immutable, i.e., once assigned, values cannot be changed. Lists, dictionaries, and sets are mutable. For example, following will give error:

 

 

String Specific Methods

 

The find method can be used to find position of a given substring in the string:

 

 

The replace method can be used to replace a substring with a given string:

 

 

The split method can be used to split a line into words based on the given delimiter. Default delimiter is space:

 

 

The upper and lower methods can be used to turn a string into upper or lower case respectively:

 

 

The isalpha and isdigit methods can be used to find whether a string is containing all alphabets or digits respectively:

 

 

The rstrip method can be used to remove white spaces at the right end of the string:

 

 

We can substitute values in a string as follows:

 

 

Related Links:

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll Up