STRING IN PYTHON

Python Free Tutorial

So far, we have covered all about introduction to python, we have written first python program “HELLO WORLD ! “, we have learnt about indentation, variables and user inputs. On our last tutorial we learnt about data types and Numeric data types like integer float and complex numbers.

Now, its time to check your knowledge. Participate in python quiz and test how far you have learnt. Check our python Quiz now !!

In this tutorial we are going learn more about Python strings. We’ll learn how to create, edit and remove lines, also learn about associate operations and string functions.Now lets start from beginning, what are string?

Strings are one of most popular aspects of python which can be create by adding single or double quotes around characters. Strings in python are created using single (‘ ‘), double (” “) or triple (”’/ “””) quotes terminated by corresponding quotes. Triple-quoted strings are useful when the contents of a string literal span multiple lines of text.

>>> corona = 'stay home ! stay safe '

In the example above, we have declared a variable corona and defined it as string value ‘stay home ! stay safe ‘ using single quote. Similarly, we can use double quote as well.

>>> corona = "I will stay home "

Imagine, if you want to change I will stay at home to I’ll stay at home . Now you will run into problems because string will ‘I’ starts and end here. And all the character after the second apostrophe python interpreter does not know what they are.

>>> corona = 'I'll stay home'
output : SyntaxError: invalid syntax

So to solve this problem, we are going to use double quotes to define our string and we have single quote in middle of our string. Example is shown below:

>>> corona = "I'll stay home"
>>> print (corona)
output: 
    "I'll stay home"

What will you do to print I stay at “home”? For this kind of problem, we are going to use single quote to define our string and use double quotes in the middle of string. Let’s see the example below:

>>> quarantine = 'I stay at "home"'
>>> print(quarantine)
 output : 'I stay at "home"'

So far we only deal with single and double quotes, what if you wanted to define multiple line strings. For example, what if you want to define a string for the message that we send in an email. In that case we are going to use triple quotes to define our string. Let see the example below:

Slicing

Slicing operator [] can be used with string. Strings are stored as sequences of characters indexed by integers, starting at zero. To extract a single character, use the indexing operator s[i] like this:

>>> s="sawid"
>>> print (s[1])

output : a

Here output is ‘a’ since s[0]=’s’, s[1]=’a’, and similarly s[4]=’d’. As square brackets can be used to access elements of the string, we can access the range of characters using slicing. To obtain certain part of characters we specify starting and ending index separated by colon ‘:’.

+---+---+---+---+---+---+ 
| P | y | t | h | o | n | 
+---+---+---+---+---+---+ 
  0   1   2   3    4   5 
 -6  -5  -4  -3   -2  -1  
>>> a = 'Python'
>>> c = a[2:4]
>>> print (c)
output : th

Here, we have assigned the starting index 2 i.e ‘t’ and ending index 4 i.e 0. But character of index 4 is ignored and only 2nd and 3rd indexed characters are shown. This extracts all characters from s[i:j] whose index is in the range i<=k<j. If either index is omitted, the beginning or end of the string is assumed, respectively: Similarly, we can use negative slicing as follows:

>>> c = a[-4:-2]
>>> print (c)
output : h

In negative slicing, starting and ending index are reverse and negative sign(-) is introduced before them.

In slicing, start is always included, and the end always excluded

Concatenation of string
>>> a = " I "
>>> b = " Love "
>>> print ( a + b + " Python")
output : I Love Python

Strings in python can be concatenated (glued together) using plus (+) operator as shown in example above. Strings aren’t interpreted as numeric data. These numeric data acts as string and can be concatenated.

>>> a = "32"
>>> print (" Output is " + a)
output: Output is 32

To perform numerical operation, string data types must be converted into Numbers using int() or float () function. Similarly, non-strings data can be converted into string using str() function. Let’s take an example

>>> a = "24"
>>> c = int(a)  # converting string to integer
>>> print ( 26+ c)
output: 50

Here string a is converted into integer using int() function and value is stored in variable c. Hence on addition operation on a, output is obtained as 50.

Two or morestring literals (i.e. the ones enclosed between quotes) next to each other are automatically concatenated. This feature is particularly useful when you want to break long strings. This only works with two literals though, not with variables or expressions.

>>> a = ‘All is ‘ ‘ well’
>>> print (a)
output : ‘All is well’
Typecasting in String
>>> a = 32
>>> c = str(a)
>>> print (type(c))
output: <class 'str'>

In the above example, integer is changed into string using str() function. str()and repr() both are used to create strings.

>>> a = 5.225
>>> print(" Using str() : ", str(a))
>>> print(" using repr() : ", repr(a))

output:
  Using str() :  5.225
  using repr() :  5.225
Formatted Strings

Formatted string in python which is used to generate dynamic text from the variables. The curly bracket in formatted string defines place holder and when we run code, these place holder gets filled with value of previously defined variables.

Here ,we define formatted string with ‘f’ and curly bracket

>>> first_name = "Diwas"
>>> last_name = "Pandey"
>>> msg = f'{first_name} {last_name} is a Ai expert'
>>> print(msg)

output:
   Diwas Pandey is a Ai expert

Let a = ‘ I love Python 123’

METHODSFUNCTIONEXAMPLE
capitalize()Converts the first character to upper casea.capitalize()
casefold()Converts string into lower casea.casefold()
count()Returns the number of times a specified value occurs in a stringa.count(‘r’)
endswith()Returns true if the string ends with the specified valuea.endswith(‘n’)
find()Searches the string for a specified value and returns the position of where it was founda.find(‘o’)
index()Searches the string for a specified value and returns the position of where it was founda.index(‘o’)
isalnum()Returns True if all characters in the string are alphanumerica.isalnum()
isalpha()Returns True if all characters in the string are in the alphabeta.isalpha()
isdecimal()Returns True if all characters in the string are decimalsa.isdecimal()
isdigit()Returns True if all characters in the string are digitsa.isdigit()
islower()Returns True if all characters in the string are lower casea.islower()
isnumeric()Returns True if all characters in the string are numerica.isnumeric()
isspace()Returns True if all characters in the string are whitespacesa.isspace()
isupper()Returns True if all characters in the string are upper casea.isupper()
lower()Converts a string into lower casea.lower()
len()Returns length of stringlen(a)
replace()Returns a string where a specified value is replaced with a specified valuea.replace(‘python’,’ai’)
startswith()Returns true if the string starts with the specified valuea.startswith(‘I’)
strip()Returns a trimmed version of the stringa.strip(“a”)
swapcase()Swaps cases, lower case becomes upper case and vice versaa.swapcase()
title()Converts the first character of each word to upper casea.title()
upper()Converts a string into upper casea.upper()

The index() method is almost the same as the find() method, the only difference is that the find() method returns -1 if the value is not found.

index() generates error sub string not found

If we need to insert characters that are illegal as string, we use ‘\’ followed by the character ( example: \@ ). Other escape characters used in python are:

SPECIAL CHARACTERFUNCTION
\’Single Quote
\\\
\nNew Line
\rCarriage Return
\bBackspace
\fForm Feed
\oooOctal value
\xhhHex value
>>> print("i love \' programming")

output:
     i love ' programming 
>>> print("I love  programming \n I love python")

output:
     I love  programming 
     I love python

This page is contributed by Diwas & Sunil . If you like AIHUB and would like to contribute, you can also write an article & mail your article to  itsaihub@gmail.com . See your articles appearing on AI HUB platform and help other AI Enthusiast.

About Diwas

🚀 I'm Diwas Pandey, a Computer Engineer with an unyielding passion for Artificial Intelligence, currently pursuing a Master's in Computer Science at Washington State University, USA. As a dedicated blogger at AIHUBPROJECTS.COM, I share insights into the cutting-edge developments in AI, and as a Freelancer, I leverage my technical expertise to craft innovative solutions. Join me in bridging the gap between technology and healthcare as we shape a brighter future together! 🌍🤖🔬

View all posts by Diwas →

7 Comments on “STRING IN PYTHON”

  1. I blog often and I really appreciate your content.
    The article has truly peaked my interest. I am going to take a note of your blog and keep checking
    for new information about once a week. I
    subscribed to your Feed too.

Leave a Reply

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