Python String with Examples

by Mar 29, 2020Python

Introduction

The string is one of the sequence data types used in python. It is an immutable object which once created can’t be altered. The string can be denoted by using a single quote (‘ ‘) or double quotes (” “) or triple quotes(” ” “).

In this article, we will know all about string in Python with examples. The contents are shown below :

Note that the value of all the strings, as displayed by the Python interpreter, is the same (‘hello’), irrespective of whether single, double or triple quotes were used for string formation. 

Since the string is a sequence data type and sequence includes an index in it starting from ‘0’ in order to search a particular item from the sequence. You will be able to see it in the following code.

Multi-line String

Python introduced multiline string using triple quotes (“””) or three single quotes(‘ ‘ ‘)

a = """ The Earth is the most
beautiful planet in the solar 
system. There're many creatures 
in our Earth."""
print(a)

Strings are Arrays

Strings in Python are arrays of bytes representing characters. Elements of strings can be accessed using square brackets([]).

Slicing

Python supports the range of characters from a string using this technique. The ratio of the starting index and the ending index separated by a semicolon can represent the slicing.

a = "Hey it's Python Tutorial"
print(a[9:15])

Negative indexing

Python also supports negative indexing to start counting from the end of the string.

Look here the index starts from “o” and ends at “i”.


Functions & Methods in String

Some predefined function and methods are there in string and by using them we can perform different kind of operations . They are :

  • len(): In order to find the length of a string we normally use this function. The following code will clear your doubts.
a = "Hello, World!"
print(len(a)) #returns 13 including white spaces and special characters
  • strip(): This method removes any white space from the beginning to the end of the string.
a = " Hey it's Python Tutorial "
print(a.strip()) # returns "Hey it's Python Tutorial"
  • lower(): This converts the entire string into lowercase.
a = "ITIKA"
print(a.lower()) #returns itika
  • upper(): This converts the entire string to uppercase.
a = "PYTHON"
print(a.upper()) #returns python
  • replace(): This replaces from one string to another.
a = "BOY"
print(a.replace("B" , "T")) #returns TOY
  • find(): This method finds the first occurrence of a substring in another string. If not found, the method returns -1.
a= "Python Tutorial"
print(a.find("Tutorial")) #returns 7
a= "Python Tutorial"
print(a.find("Myname")) #returns -1
  • count(): This method returns the number of occurrences of a substring in the given string.
a = " " "Meghna wakes up in the morning. Meghna brushes her teeth. Meghna reads books" " "
print(a.count("Meghna")) #returns 3
  • isdigit(): This method returns true if all the characters in the string are digits (0-9) if not, it returns false.
a ='2020'
print(a.isdigit()) #returns true
a='26/03/2020'
print(a.isdigit()) #returns false

List of string Methods

  • capitalize()
  • casefold()
  • count()
  • encode()
  • endswith()
  • expandtabs()
  • find()
  • format()
  • format_map()
  • index()
  • isalpha()
  • isalnum()
  • isdecimal()
  • isdigit()
  • isidentifier()
  • upper()
  • lower()
  • isnumeric()
  • join()
  • isspace()
  • isprintable()
  • replace()
  • partition()
  • rfind()
  • rindex()
  • rjust()
  • Istrip()
  • Ijust()
  • rpartition()
  • rsplit()
  • rstrip()
  • split()
  • strip()
  • startswith()
  • swapcase()
  • title()
  • translate()
  • zfill()
  • splitliness

String Operators

Arithmetic operators don’t operate on strings. However, there are special operators for string processing.

  • “+”: Appends the second string to the first
 a='hello'
 b='world' #returns a+b
  • “*”: Concatenates multiple copies of the same string
a='hello'
a*3 #returns 'hellohellohello'
  • “[: ] “: Fetches the characters in the range specified by two index operands separated by the: symbol
a = 'Python Tutorials'
a[7:16] #returns 'Tutorials'
  • “[] “: Returns the character at the given index
a = 'Python Tutorials'
a[7] # returns T

String Check

To check whether a particular character or a phrase is present in a string or not we use in and not in.

#Check if the phrase "ain" is present in the following text
a = "India is also following the global phenomenon."
x = "also" in a
print(a) #returns True
#Check if the phrase "also" is not present in the following text
a = "India is also following the global phenomenon."
x = "also" not in a
print(a) #returns False

String Format

We can combine strings and numbers by using the format() method. The format() method takes the passed arguments, formats them, and places them in the string where the placeholders { }  are:

quantity = 3
item = 567
price = 49.95
order = "I want {} pieces of item {} for {} rupees."
print(order.format(quantity, item, price)) #returns I want 3 pieces of item 567 for 49.95 #rupees.

Escape Character

An escape character is a backslash  \  followed by the character you want to insert.

We will get an error if we use a double quote inside a double quote like this :

But, if we use “\ \” it will not generate any error

The list of escape characters in a string:

  • \ – for a single quote
  • \\ – for double quote
  • \n – newline
  • \r – Carriage Return
  • \t – for tab
  • \b -for backspace
  • \f – Form Feed
  • \ooo – Octal value
  • \xhh – Hex value

Creating a multiplication Skill in Alexa using python

Written By Itika Sarkar

Hey, this is Itika Sarkar. I'm currently pursuing BTech degree in Electronics & Communication Engineering(2nd year). Writing technical articles, tutorial and innovative projects on modern industry-related technologies are my hobbies.

RELATED POSTS

Python Regular Expression

Python Regular Expression

Python is a general-purpose high-level programming language. Python is mainly used as a support language to software developers. It helps in building control and management and also in testing. The syntax python uses is very simple and similar to the English language....

Introduction to MicroPython and ESP8266

Introduction to MicroPython and ESP8266

For ages, C and C++ have ruled over the embedded system industry. Fast prototyping is an important aspect of the industry today. In fact MicroPython is the best suited for fast prototyping. Students and engineers are becoming very familiar with the Python programming...

Five Best Python Projects for Beginners

Five Best Python Projects for Beginners

Learning and practicing of any programming language can be monotonous. Also, only learning can not be the perfect gain of knowledge if we don't put it into some implementation. Likewise, Python programming language can be interesting but until we don't use it in some...

How to convert .py into .pyc? Compilation of Python Code

How to convert .py into .pyc? Compilation of Python Code

In this article we will see what is a pyc file ,how is it formed,how to convert and compile a pyc file. When we run a code in python it actually goes through a couple of steps before our program reaches the virtual machine It is compiled to bytecode.Then it is...

How to create and install a Python Package?

How to create and install a Python Package?

Requirements Check the tools pip --version pip install wheel What is Python Package Index? What is Distutils? Creating a Package Directory Structure some_root_dir/ |-- README |-- setup.py |-- an_example_pypi_project | |-- __init__.py | |-- useful_1.py | |--...

Docker for beginners tutorial:

Docker for beginners tutorial:

What is Docker? Docker, in simple words is a tool that allows developers who build applications, to package them with all their dependencies into a ‘container’ which can easily be shipped to run on the host operating . Containers do not have high overhead and allow...

Object-Oriented Programming in Python

Object-Oriented Programming in Python

Python Classes and Methods Python is an object-oriented programming language. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made....

Python Flask Tutorial

Python Flask Tutorial

Flask is a web framework that provides libraries to build lightweight web applications in python. It is developed by Armin Ronacher who leads an international group of Python enthusiasts (POCCO). Contents What is Flask? Flask Environment Setup First Flask...

Python Numbers

Python Numbers

In this article you will learn about types of numbers in python and their mathematical operations. So these are the contents of this article : Introduction Decimal Need of DecimalFractionsMathematics Introduction Python supports integer, floating-point number and...

Python File Handling

Python File Handling

In this article, we will discuss all about file handling in Python. Let us have a quick look at the contents shown below: IntroductionFile openSyntaxRead filesParts of file to readRead linesloopChoose filesWrite filesAppendSplitting wordsCreate a new fileSeek...

Python Lambda

Python Lambda

In this article, we will discuss on Python lambda. Let us have a quick look on the following contents shown below: IntroductionAdd two numbers using LambdaSum of 10 natural numbersMultiplicationSmaller of two numbers Introduction Lambda functions are the anonymous...

Python Functions

Python Functions

In this article, we will tell about Python functions. We should also know about function defining function calling and variable arguments. Let's have a quick look on the below contents : IntroductionFunction CreationDefinitionDeclarationCallArgumentsRequired...

VIDEOS – FOLLOW US ON YOUTUBE

EXPLORE OUR IOT PROJECTS

IoT Smart Gardening System – ESP8266, MQTT, Adafruit IO

Gardening is always a very calming pastime. However, our gardens' plants may not always receive the care they require due to our active lifestyles. What if we could remotely keep an eye on their health and provide them with the attention they require? In this article,...

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

All you need to know about integrating NodeMCU with Ubidots over MQTT

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

All you need to know about integrating NodeMCU with Ubidots over Https

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

How to design a Wireless Blind Stick using nRF24L01 Module?

Introduction Let's learn to design a low-cost wireless blind stick using the nRF24L01 transceiver module. So the complete project is divided into the transmitter part and receiver part. Thus, the Transmitter part consists of an Arduino Nano microcontroller, ultrasonic...

Sending Temperature data to ThingSpeak Cloud and Visualize

In this article, we are going to learn “How to send temperature data to ThingSpeak Cloud?”. We can then visualize the temperature data uploaded to ThingSpeak Cloud anywhere in the world. But "What is ThingSpeak?” ThingSpeak is an open-source IoT platform that allows...

Amaze your friend with latest tricks of Raspberry Pi and Firebase

Introduction to our Raspberry Pi and Firebase trick Let me introduce you to the latest trick of Raspberry Pi and Firebase we'll be using to fool them. It begins with a small circuit to connect a temperature sensor and an Infrared sensor with Raspberry Pi. The circuit...

How to implement Machine Learning on IoT based Data?

Introduction The industrial scope for the convergence of the Internet of Things(IoT) and Machine learning(ML) is wide and informative. IoT renders an enormous amount of data from various sensors. On the other hand, ML opens up insight hidden in the acquired data....

Smart Display Board based on IoT and Google Firebase

Introduction In this tutorial, we are going to build a Smart Display Board based on IoT and Google Firebase by using NodeMCU8266 (or you can even use NodeMCU32) and LCD. Generally, in shops, hotels, offices, railway stations, notice/ display boards are used. They are...

Smart Gardening System – GO GREEN Project

Automation of farm activities can transform agricultural domain from being manual into a dynamic field to yield higher production with less human intervention. The project Green is developed to manage farms using modern information and communication technologies....