Python Strings




Python Strings


We have covered the number data type in the last article and now we are going to study about strings. Strings are a sequence of characters enclosed between either single quotes or double-quotes. eg. 'Hello' "Linux Advise"



Strings


String literals in python are surrounded by either single quotation marks or double quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:


Example:


print("Hello")
print('Hello')

Output:


Hello
Hello


Because strings are ordered sequences, we can use slicing and indexing to grab sub-section of the string.

Indexing notation uses [] notation after the string.

Indexing allows you to grab a single character from a string



Assign String to a Variable


Assigning a string to a variable is done with the variable name followed by an equal sign and the string:


Example:


a ="Hello"
print(a)

Output:


Hello



Multi-line Strings


You can assign a multi-line string to a variable by using three quotes:


Example:

You can use three double quotes:


a ="""Welcome to Linux advise
this article is for python string operations
and functions """
print(a)

Output:


Welcome to Linux advise
this article is for python string operations
and functions


Example:


Or three single quotes:


a ='''Welcome to Linux advise
this article is for python string operations
and functions'''
print(a)

Output:


 Welcome to Linux advise
 this article is for python string operations 
 and functions
 


How to access characters in a string?

  • We can access individual characters using indexing and a range of characters using slicing. The index starts from 0.

  • Trying to access a character out of index range will raise an IndexError. The index must be an integer.

  • We can't use floats or other types, this will result into TypeError.

  • Python allows negative indexing for its sequences.

  • The index of -1 refers to the last item, -2 to the second last item, and so on. We can access a range of items in a string by using the slicing operator :(colon).


Example:


# Accessing string characters in Python
str = 'Linux Advise'
print('str = ', str)

Output:


str =  Linux Advise 


Example:


# First character
print('str[0] = ', str[0])

Output:


str[0] =  L 


Example:


# Last character
print('str[-1] = ', str[-1])


Output:


str[-1] =  e


Example:


# Slicing 2nd to 5th character
print('str[1:5] = ', str[1:5])

Output:


str[1:5] =  inux 


Example:


# Slicing 6th to 2nd last character
print('str[5:-2] = ', str[5:-2])

Output:


str[5:-2] =   Advi



If we try to access an index out of the range or use numbers other than an integer, we will get errors.


Example:


# Index must be in range
my_string = 'Linux Advise'
my_string[15]  

Output:


Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
IndexError: string index out of range
 

Example:


# Index must be an integer
my_string = 'Linux Advise'
my_string[1.5] 


Output:


Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: string indices must be integers
 


Python String Operations


There are many operations that can be performed with a string which makes it one of the most used data types in Python.


We can do a number of operations on strings.


  • If in case the string consists of a single quote, then string should be placed between double quotes


Example:


print("I don't lie") 

Output:


I don't lie


  • We can have newlines and Tab-separated strings as well as shown below


Example:


print("Welcome \n to \n Linux \n Advise ")
Output:
Welcome 
to 
Linux 
Advise 

print("Welcome \t to \t Linux \t Advise ")
Output:
Wecome 	 to 	 linux 	 Advise 



Concatenation of Two or More Strings


Joining of two or more strings into a single one is called concatenation.

The + operator does this in Python. Simply writing two string literals together also concatenates them.

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


Example:


# Python String Operations
str1 = 'Linux'
str2 ='Advise'
# using +
print('str1 + str2 = ', str1 + str2)

Output:


str1 + str2 =  LinuxAdvise 



Example:


# Using *
print('str1 * 3 =', str1 * 3)

Output:


str1 * 3 = LinuxLinuxLinux



To calculate the length of the string we can use len() function


Example:


len("linuxadvise")

Output:


11



The format() Method for Formatting Strings


The format() method that is available with the string object is very versatile and powerful in formatting strings. Format strings contain curly braces {} as placeholders or replacement fields that get replaced.

We can use positional arguments or keyword arguments to specify the order.



Example:


# Python string format() method
# Default(implicit) order
default_order = "{}, {} and {}".format('John','Bill','Sean')
print(&#x