• Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements
CODE OF GEEKS

We at CODE OF GEEKS, aim at providing best and quality content for our users at no extra cost.

    • Study Materials
      • InfyTQ Archive
      • Infosys Archive
      • TCS Archive
      • Accenture Archive
      • AMCAT Archive
      • Capgemini Archive
      • Cisco Archive
      • CoCubes Archive
      • Cognizant(CTS) Archive
      • Deloitte Archive
      • DXC Archive
      • Goldman Sachs Archive
      • Hexaware Technologies Archive
      • LTI Archive
      • MindTree Archive
      • Virtusa Archive
      • Wipro Archive
    • Interview Preparation
      • C Interview Questions
      • Data Structures Interview Questions
      • DBMS Interview Questions
      • HR Interview Questions
      • Java Interview Questions
      • Operating System Interview Questions
      • Python Interview Questions
      • SQL Query Interview Questions
    • Tutorials
      • Node.js Tutorial
      • Express.js Tutorial
      • Python Tutorial
    • Programming
      • C Programming MCQs
      • C Code Snippets – Output Questions
      • Python Code Snippets – Output Questions
      • Java Code Snippets – Output Questions
    • Aptitude
      • Verbal Ability for Placements
CODE OF GEEKS
CODE OF GEEKS
  • Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements

Strings in Python, Slicing and Basic Operations on Python Strings

  • January 18, 2022
  • CODE OF GEEKS
  • 0

Python Strings: In this Unit…

  • Strings in Python, Slicing and Basic Operations
  • String Immutability Explained
  • strip() method in Strings
  • find() method in Strings
  • count() method in Strings
  • replace() method in Strings
  • split() method in Strings
  • Switching Cases in Strings
  • startswith() method in Strings
  • endswith() method in Strings

Video Illustration

Strings in Python refers to the collection of characters like digits, lower-case alphabets, upper-case alphabets, special letters, etc.

Example of Strings in Python : “Hello”, ‘World 3123’

Generally, A Python String is enclosed under ‘ ‘ (single quotes) or under ” “(double quotes) as shown in above example. Sometimes, we use ”’ (triple quotes) as well, this is to represent a multiline string.

”’ Hello, This is
a multi-line string”’

In Python, keyword str represents a string. We can typecast any of the datatype to string via str().

Like,

num = 10 
print("Type before typecasting : ", type(num))
num = str(num)
print("Type after typecasting : ", type(num))

O/P

Type before typecasting : <class ‘int’>
Type after typecasting : <class ‘str’>

When we assign a string value to a Python variable then it is referred to as String object (String Literal).

s = "Hello" 

Here, ‘s’ is the string object.

Strings are immutable. Immutable objects are the objects whose content can not be changed.

Length of a Python String

To find the length of a given string we use len() function in Python.

site = "CODE OF GEEKS"
l = len(site)
print(l)

O/P : 13

Here, ‘site’ is the string name whose length is computed using len() function.

Indexing in Python String

Just like arrays, list, set, indexing of string characters also starts with ‘0’.

Consider a sample string site = ‘Code of Geeks’

Indexing in Strings

In the above table, row 1 represents positive indexes, row 2 represents string characters and row 3 represents negative indexes. Python String also supports negative indexing. Like,

site[0] = site[-13] = ‘C’
site[12] = site[-1] = ‘s’


Traversing a Python String

1. Using while loop

site = 'Code of Geeks'
i = 0
while(i < len(site)):
    print(site[i], end='')
    i+=1

O/P : Code of Geeks

Here, in the above code, we are running a while loop from Index 0 to Index len(site)-1. Also, value at index ‘i’ is accessed as ‘site[i]’.

In Reverse Order

site = 'Code of Geeks'
i = len(site)-1
while(i >= 0):
    print(site[i], end='')
    i-=1

O/P : skeeG fo edoC

Here, in the above code, we are running a while loop from Index len(site)-1 to 0. Also, value at index ‘i’ is accessed as ‘site[i]’.

2. Using for loop

site = 'Code of Geeks'
for i in range(0, len(site)):
    print(site[i], end='')
    i+=1

O/P : Code of Geeks

Here, in the above code, we are running a for loop from Index 0 to Index len(site)-1. Also, value at index ‘i’ is accessed as ‘site[i]’.

In Reverse Order

site = 'Code of Geeks'
for i in range(len(site)-1,-1, -1):
    print(site[i])
    i+=1

O/P : skeeG fo edoC

Here, in the above code, we are running a for loop from Index len(site)-1 to 0 using range() function. Also, value at index ‘i’ is accessed as ‘site[i]’.

3. Using in operator with for loop

site = 'Code of Geeks'
i = 0
for i in site:
    print(i, end='')

O/P : Code of Geeks

Here, object ‘i’ stores a character itself, instead of storing an index.


Slicing in Python

Slicing in Python is the process of breaking a string into slices or parts. Typically, Slicing works in the following way :

string_name[start : stop : stepsize]

start : It denotes the starting position where string slicing starts.
stop : It denotes the ending position where string slicing ends.
stepsize : It denotes the number of elements to be skipped. It is optional

By default, slicing is done from 0th to (n-1)th element of a string, keeping stepsize as 1.

string_one = 'CODE OF GEEKS'
string_two = string_one[0 : 9 : 1] 
print(string_two)

O/P : CODE OF G

In the code provided, string_one is sliced from 0 to (9-1).

Keeping stepsize as 2 :

In this case, slicing is done from 0th to (n-1)th element of a string, keeping stepsize as 2.

string_one = 'CODE OF GEEKS'
string_two = string_one[0 : 9 : 2] 
print(string_two)

O/P : CD FG

In the code provided, string_one is sliced from 0 to (9-1).


We all know, String Slicing is bit complicated, let’s check out some more examples

s = 'CODE OF GEEKS'
print(s[::]) # to access string from 0th to last character, prints 'CODE OF GEEKS'
print(s[::2]) # to access string from 0th to last character in steps of 2, prints 'CD FGES'
print(s[2::]) # to access string from s[2] to last character, prints 'DE OF GEEKS'
print(s[:4:]) # to access string from s[0] to s[3], prints 'CODE'

Also, it is possible to use reverse slicing in order to access string in reverse order. Let’s see few examples for negative slicing as well.

s = 'CODE OF GEEKS'
print(s[::-1]) # to access string in reverse order 
print(s[-4:-1]) # to access string from s[-4] to s[-2] from left to right, prints 'EEK'  
print(s[-7::]) # to access string from s[-7] to end of the string, prints 'F GEEKS'

When step size is negative, then elements are counted from right to left.

s = 'CODE OF GEEKS'
print(s[-1:-4:-1]) # to access string from s[-1] to s[-3] from right to left, prints 'SKE'
print(s[-3:-7:-1]) # to access string from s[-3] to s[-6] from right to left, prints 'EEG ' 

Repeating the Strings in Python

We use ‘*’ operator to repeat a string ‘n’ number of times.

s = "py"
print(s*3) 

Above code returns ‘pypypy‘ as an output.

You can define any integer value in place of 3.

Concatenation of Strings in Python

Concatenation (in String) is the process of attaching/ appending two or more strings to form a resultant string. We can do it in following ways

1. Using + operator

s1 = "Hello"
s2 = " " 
s3 = "Geek"
s4 = s1 + s2 + s3
print("Concatenated String : ", s4)

O/P :

Concatenated String : Hello Geek


Comparing Strings in Python

We can compare two or more strings with the help of relational operators like >, <. >=, <=, ==, or != operators. They return boolean value depending upon the strings that are being compared.

While comparing the strings, Python Interpreter compares them by taking them in English Dictionary order. String that comes first in dictionary will have low value than the string that comes next.

Let us see one example to understand this.

s1 = "India" 
s2 = "Bharat" 
if s1 == s2: 
    print("s1 == s2")
elif s1>s2:
    print("s1 > s2")
else:
    print("s1 < s2")

O/P : s1 > s2

If we check the two strings it is clear that they are not equal also “Bharat” has lower value than “India” when arranged lexicographically. Hence, s1 > s2.

Formatting Strings in Python

Formatting in Strings can be done to refactor or to display a string in a clearer way. We can customize our strings in a dynamic way using String Formatting. It allows us to integrate the values as a part of string that are not defined in the code.

Old school way :

We can use ‘%’ to achieve this.

s = "Baby"
print("Hey, sort me %s " % s)

O/P

Hey, sort me Baby

We can use ‘%d‘ to display integer values.

print("Hey, I am %d " % 10)

O/P

Hey, I am 10

And to print, float values as well

n = 1231.3131313
print('The value of x is %.2f' %n) # 2 decimal places
print('The value of x is %.4f' %n) # 4 decimal places

O/P

The value of x is 1231.31
The value of x is 1231.3131

The newer way… format() function

s1 = 'baby'
s2 = 'fight'
print("Hello {0} wanna {1}".format(s1, s2))
print("Hello {} wanna {}".format(s1, s2))
print('{}{}'.format(s1, s2))
print('{} - {}'.format(s1, s2))

O/P

Hello baby wanna fight
Hello baby wanna fight
babyfight
baby – fight

So, that’s all we have in this lesson. See you in the next..


  • Previous Java Programming Mock Test Series
  • Next Hedger

Leave a Reply Cancel reply

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

Advertise with us

Table of Content – Python

  1. Introduction to Python ▼
    • Python and its features
    • Key Differences : C vs Python
    • Key Differences : Java vs Python
    • Python Flavors
    • PVM and Memory Management in Python

  2. Python Fundamentals ▼
    • 'Hello World' using Python
    • Comments in Python
    • Variables and Garbage Collection in Python
    • Datatypes in Python
    • Determining the Datatype of Literal | type() method
    • Tokens in Python
    • Keywords in Python
    • Identifiers and Naming Convention in Python
    • Literals in Python

  3. Python Operators ▼
    • Operators in Python
    • Python Mathematical Functions

  4. Python User Inputs ▼
    • Taking Inputs | input() function in Python

  5. Python Control Statements ▼
    • Control Statements in Python
    • if-elif-else Statements in Python
    • Looping in Python
    • while loop in Python
    • while-else loop in Python
    • for loop in Python
    • for-else loop in Python
    • Infinite loops in Python
    • Nested loops in Python
    • break Statement in Python
    • continue Statement in Python
    • pass Statement in Python
    • assert Statement in Python
    • return Statement in Python

  6. Python Functions ▼
    • Introduction to Python Functions
    • Python Functions vs Python Methods
    • Local and Global Variables in Python
    • Formal and Actual Arguments in Python
    • Recursion in Python Functions
    • Lambda Functions in Python
    • Function Decorators in Python
    • Function Generators in Python

  7. Python Strings ▼
    • Strings in Python and Basic Operations
    • String Immutability Explained
    • strip() method in Strings
    • find() method in Strings
    • count() method in Strings
    • replace() method in Strings
    • split() method in Strings
    • Switching Cases in Strings
    • startswith() method in Strings
    • endswith() method in Strings

  8. Python Lists ▼
    • Python Lists Basics
    • index() method in list
    • append() method in list
    • insert() method in list
    • copy() method in list
    • remove() method in list
    • pop() method in list
    • sort() method in list
    • reverse() method in list
    • clear() method in list
    • Nested Lists in Python
    • List Comprehensions in Python

  9. Python Sets ▼
    • Python Sets and Basic Operations
    • Adding Elements in Python Sets
    • Removing Elements in Python Sets
    • Union in Python Sets
    • Intersection in Python Sets

  10. Python Tuples ▼
    • Python Tuple Basics
    • Python Tuples Immutability Explained
    • Python Tuples Methods
    • Python Nested Tuples

  11. Python Dictionary ▼
    • Python Dictionary Basics
    • Python Dictionary Sorting
    • Python Dictionary List to Dictionary Conversion
    • Passing Dictionary to Function

  12. Python Classes and Objects ▼
    • Classes and Objects
    • self variable in Python
    • __init__() method in Python
    • Inner Classes
    • Instance variable and methods
    • Class variable and methods

  13. Python OOPs ▼
    • Inheritance and its types
    • super() method in Python
    • Abstract class| Abstract method in Python

  14. Python Exception Handling ▼
    • Errors in Python and its types
    • Exception Handling in Python
    • Types of Exceptions in Python
    • Custom Exceptions in Python

  15. Python File Handling ▼
    • File Handling in Python
    • with statement in Python

  16. Python DateTime Modules ▼
    • datetime module in Python

  17. Python MultiThreading ▼
    • Multithreading in Python

  18. Python Requests Module ▼
    • Python GET Request
    • Python POST Request
    • Python PUT Request

Python Programs

  1. Fibonacci Series till 'N' Numbers

  2. Sum of Digits of a Number

  3. Checking Prime Number

  4. Checking Armstrong Number

  5. Finding Reverse Number (Traditional)

  6. Finding Reverse Number (Pythonic)

  7. Finding Prime Numbers within Range

  8. Finding Prime Numbers within Range Using SOE

  9. Checking Leap year

  10. Calculating Simple Interest

  11. Generate Random Numbers

  12. Calculate Compound Interest

  13. Area of Circle

  14. ASCII Value of Character
CODE OF GEEKS

Subscribe to Newsletter

CODE OF GEEKS

Learn | Code | Achieve

Reach us

[email protected]
We at CODE OF GEEKS, aim at providing quality content to our users at no cost.
CODE OF GEEKS

Important Pages

About us
Advertise
Privacy Policy
Terms and Conditions
Refund Policy
Contact us

Placements – Study Materials

TCS NQT     Wipro     CapGemini
Accenture     MindTree     CTS
DXC     Hexaware Technologies     AMCAT
CoCubes     Goldman Sachs     Dell
Cisco     Deloitte     Virtusa     LTI     Infosys   

Tutorials

Python
Node.js
Express.js
Golang

Recent Posts

Strings in Go and its basic operations
  • August 11, 2023
Introduction to Functions in Go programming
  • August 11, 2023

Copyright @ CODE OF GEEKS. All Rights Reserved.