Python Basic – How to use String in python

Home /

Table of Contents

What is String in python?

The string is the most important data type in Python. A set of characters or some word sequences is usually called a string. In Python, any sentence can be used as a string with single ( ‘ ‘ ), double ( ” ” ) or triple (“” “” “”) quotations. f you type a sentence like the one below and press Enter, you can see that sentence in the output.

   >>> "Welcome to EnableGeek"
   'Welcome to EnableGeek'
   >>> 'Python is a powerful programming language.'
   'Python is a powerful programming language.'

Whether a double or single quotation is used when giving input, it shows that string with a single quote at the output.

Some characters cannot be used directly in a string. For example, a string or sentence indicated by a double quote cannot contain a double quote. This will give Python an error. In this case, such characters escaped with a backslash (\) sign in front of them. 

   >>> 'Karim\'s mother: He\'s a very clever boy!'
   "Karim's mother:  He's a very clever boy!"

Newline characters (\n), backslash characters (\), tabs, Unicode characters – all of these have to be escaped and used in strings.

In Python, Newline characters need to be written manually, unless the string or sentence containing more than one line is defined into three quotations. Let’s look at the example below.

   >>> """Rahim: Hello, How are you?
   ... Karim: I'm fine. What about you?"""
   "Rahim: Hello, How are you?\nKarim: I'm fine. What about you?"

Above, I have given a string with two lines as input and the output shows that Python has automatically placed (\n) characters in the string where the new line is needed.

Special characters and escape sequences

Below are some common escape sequences:

                      Sequence                Description
                   \\A Backslash to be executed
                    \’Single quote
                  \”Double quote
                  \nLine Break
                  \vVertical Tab

Basic input-output

In Python, we use some special functions for data input and output. The basic functions of input and output are

  • input()
  • print()

Input function input ()

We usually use this function to get input from the user. I hope the matter will be clearer by giving an example.

   >>> input("What is your passion? ")
   What is your passion? To be a python programmer.
   'To be a python programmer.'

In this case, when the Python interpreter executes the code, the interpreter will wait for the user’s input and receive the input data until the user presses the Enter button or another newline character appears in the input. If the above statement is executed on the console, then pressing Enter will bring up the ‘To be a Python programmer.‘ output in the bottom line, which was taken as input from the user.

Output function print ()

The print () function only produces what is given as its argument. A few examples will make the matter of output easier.

   >>> print('I am a learner.')
   I am a learner.

The output of the above program will be as usual ‘I am a learner.’.

 String Operation


As with integers or floats, strings can also be added, which is called concatenation.

   >>> "Enable" + "Geek"
   >>> "I am a programmer" + "," + "programming is my passion!"
   'I am a programmer,programming is my passion!'

But no string can be added to any number,

   >>> "38" + "10"
   >>> 38 + "10"
   Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   TypeError: unsupported operand type(s) for +: 'int' and 'str'

In the first operation “38” and “10” are both strings. So the two have been added to the concatenation operation. But in the next operation, 38 is an integer and 10 is a string so it is not possible to add or concatenate two different types of data.


Multiplication can also be done with strings like addition, it is called repetition. However, this multiplication must be an integer number with a string. not between strings and strings or with float-type data.

   >>> "EnableGeek " * 3
   'EnableGeek EnableGeek EnableGeek '
   >>> "10110" * 8
   >>> "10110-" * 8

String formatting

The ‘format’ method is used to create beautiful string output by combining string-type data with non-string data. This allows some of the arguments in a string to be replaced or substituted. Each of the arguments in the format method replaces the placeholders between the strings in front of it. Placeholders are defined using an index or name 

with { }. 

An example will make the point clear

   >>> msg = "My marks on Math: {0}, Physics: {1}, Chemistry: {2}".format(89, 81, 94)
   >>> print(msg)
   My marks on Math: 89, Physics: 81, Chemistry: 94

When formatting the indexes 0, 1, and 2, … This is how to give serial, but not in this manner. If desired, these can be given before, after, or more than once.

   >>> '{2}, {0}, {1}'.format('First', 'Second', 'Third')
   'Third, First, Second'
   >>> '{0}{1}{0}'.format(" Geek ", "Enable")
   ' Geek Enable Geek '

This can also be done by sending named arguments in the format method and using those names as placeholders within the string.

   >>> msg = "If A = {x} and B = {y}, then A+B = {z}".format(x = 38, y = 10, z = 38+10)
   >>> print(msg)
   If A = 38 and B = 10, then A+B = 48

Some Important Functions

Below are some examples of important and useful functions for working with strings.

The join(“ ”) method combines the strings of a list with a string (the list is discussed later) but uses a separator set in the middle. DevOps, Cloud, and Pipeline are combined in the following example, but with a comma (,) separator between them.

   >>> print(", ".join(["DevOps", "Cloud", "Pipeline"]))
   DevOps, Cloud, Pipeline

Find a substring using the replace(“ ”) method and replace it with something else. As in the example below – EnableGeek has been replaced by the world.

   >>> print("Hello World".replace("World", "EnableGeek"))
   Hello EnableGeek

The split(” “) method is the opposite of the join(” “) method. This means that a list can be made by breaking a sentence subject to a specific separator through this method. That is shown in the following example.

   >>> print("e, n, a, b, l, e, g, e, e, k".split(", "))
   ['e', 'n', 'a', 'b', 'l', 'e', 'g', 'e', 'e', 'k']

The startswith (” “), endswith (” “) method can be used to check whether a sentence has a beginning or end with a specific substring. The upper (” “) method converts all the characters in the string to uppercase. Similarly, the lower (” “) method converts all the characters into lowercase.

   >>> print("EnableGeek is awesome.".startswith("EnableGeek"))
   >>> print("EnableGeek is awesome.".startswith("is"))
   >>> print("EnableGeek is awesome.".endswith("awesome."))
   >>> print("EnableGeek is awesome.".endswith("Geek"))
   >>> text = "EnableGeek"
   >>> print(text.upper())
   >>> print(text.lower())

String Interpolation

You can also use the f-string method for interpolating a string. This is the most modern and recommended way of string interpolation in Python 3.6+. You can place the variable or expression inside curly braces {} within the string and prefix the string with the letter f.

>>> mark = 80
>>> name = "John"
>>> print(f"{name} got {mark} marks!")
John got 80 marks!

Share The Tutorial With Your Friends

Check Our Ebook for This Online Course

Advanced topics are covered in this ebook with many practical examples.

Other Recommended Article