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('\n--- Default Order ---')
print(default_order)

Output:


--- Default Order ---
John, Bill and Sean


Example:


# Order using positional argument
positional_order = "{1}, {0} and {2}".format('John','Bill','Sean')
print('\n--- Positional Order ---')
print(positional_order)

Output:


--- Positional Order ---
Bill, John and Sean


Example:


# Order using keyword argument
keyword_order = "{s}, {b} and {j}".format(j='John',b='Bill',s='Sean')
print('\n--- Keyword Order ---')
print(keyword_order)

Output:


--- Keyword Order ---
Sean, Bill and John



Example:


my_str = "Hello, my name is {} and I live in {}"
my_str.format('piyush','India')

Output:


Hello , my name is piyush and I live in India



Common Python String Methods


There are numerous methods available with the string object. The format()method that we mentioned above is one of them. Some of the commonly used methods are lower(),upper(),join(),split(),find(),replace()etc


Below are some examples to help you in better understanding strings.


Example:


# We will now define a  string
my_str = "This is my first string"
# Now we will print the string
print(my_str)

Output:


This is my first string



Example:


# Now we will append something to the existing string and
# Print it again
my_new_str = my_str + "  which is now modified"
print(my_new_str)

Output:


This is my first string  which is now modified



Example:


## STRING AND STRING OPERATORS


# String concatenation
str1 = "pass"
str2 = "word"
str3 = str1 + str2
print("New string is :", str3)

Output:


New string is : password


Example:


# String Multiplication
str4 = "Ha"
str5 = 5 * str4
print("The string after multiplication is : ", str5)

Output:


The string after multiplication is :  HaHaHaHaHa


Example:


# Convert string to upper case
str6 = "piyush"
print("The string when converted to uppercase looks like :" , str6.upper())

Output:


The string when converted to uppercase looks like : PIYUSH


Example:


# Convert string to lower case -> use lower() function
print ("I \t am \t learning \t python")

Output:


I 	 am 	 learning 	 python



Example:


print("Below days are my weekly offs: \nSaturday \nSunday")

Output:


Below days are my weekly offs: 
Saturday 
Sunday


Example:


print("'We are now printing a single quoted statement'")

Output:


'We are now printing a single quoted statement'



Example:


print('"We are now printing a double quoted statement"')

Output:


"We are now printing a double quoted statement"


Example:


 my_str = "I love my country"
 print(my_str)

Output:


 I love my country
 

Example:


print(my_str[0])

Output:


 I
 

Example:


print(my_str[2])


Output:


 l


Example:


 print(my_str[-1])

Output:


 y
 

Example:


 print(my_str[-3])

Output:


 t
 

Example:


 print(my_str[2:8])

Output:


 love m



Example:


 print(my_str[:5]) 
# this means start from 0 index and go up to and not including 5 index

Output:


 I lov



Example:


print(my_str[::3]) 
# Go from beginning till the end with a step size of3

Output:


 Io ur
 

Example:


 ## [a:b:c] a = start b = stop c = step size
 print(my_str[::-1]) # This will reverse a string
 

Output:


 yrtnuoc ym evol I


I hope you got a nice understanding of strings in Python.


Next datatype is List.

Keep Reading :)







44 views0 comments
 

Subscribe Form

©2020 by Linux Advise