Python strings: A Concise Tutorial Just An Hour | ACTE
Python strings

Python strings: A Concise Tutorial Just An Hour – FREE

Last updated on 19th Jul 2020, Blog, Tutorials

About author

Vinoth (Python Developer, HCL )

Jump to More Information - (string) The author's field from the current author's DB object, otherwise an empty string.

(5.0) | 15424 Ratings 1885

In this tutorial you will learn to create, format, modify and delete strings in Python. Also, you will be introduced to various string operations and functions.

What is String in Python?

A string is a sequence of characters.A character is simply a symbol. For example, the English language has 26 characters. Computers do not deal with characters, they deal with numbers (binary). Even though you may see characters on your screen, internally it is stored and manipulated as a combination of 0s and 1s.
This conversion of character to a number is called encoding, and the reverse process is decoding. ASCII and Unicode are some of the popular encoding used. In Python, a string is a sequence of Unicode characters. Unicode was introduced to include every character in all languages and bring uniformity in encoding. You can learn about Unicode from Python Unicode.

How to create a string in Python?

Strings can be created by enclosing characters inside a single quote or double-quotes. Even triple quotes can be used in Python but generally used to represent multiline strings and docstrings.

  • # defining strings in Python
  • # all of the following are equivalent
  • my_string = ‘Hello’
  • print(my_string)
  • my_string = “Hello”
  • print(my_string)
  • my_string = ”’Hello”’
  • print(my_string)
  • # triple quotes string can extend multiple lines
  • my_string = “””Hello, welcome to
  •            the world of Python”””
  • print(my_string)

Run Code

When you run the program, the output will be:

Hello

Hello

Hello

Hello, welcome to the world of Python

How to access characters in a string?

We can access individual characters using indexing and a range of characters using slicing. 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).

  • #Accessing string characters in Python
  • str = ‘programiz’
  • print(‘str = ‘, str)
  • #first character
  • print(‘str[0] = ‘, str[0])
  • #last character
  • print(‘str[-1] = ‘, str[-1])
  • #slicing 2nd to 5th character
  • print(‘str[1:5] = ‘, str[1:5])
  • #slicing 6th to 2nd last character
  • print(‘str[5:-2] = ‘, str[5:-2])

Run Code

When we run the above program, we get the following output:

str =  programiz

str[0] =  p

str[-1] =  z

str[1:5] =  rogr

str[5:-2] =  am

If we try to access an index out of the range or use numbers other than an integer, we will get errors.

  • # index must be in range
  • >>> my_string[15]  

IndexError: string index out of range

  • # index must be an integer
  • >>> my_string[1.5] 

TypeError: string indices must be integers

Slicing can be best visualized by considering the index to be between the elements as shown below.

    Subscribe For Free Demo

    [custom_views_post_title]

    If we want to access a range, we need the index that will slice the portion from the string.

    Element Slicing in Python

    String Slicing in Python

    How to change or delete a string?

    Strings are immutable. This means that elements of a string cannot be changed once they have been assigned. We can simply reassign different strings to the same name.

    • >>> my_string = ‘programiz’
    • >>> my_string[5] = ‘a’

    TypeError: ‘str’ object does not support item assignment

    • >>> my_string = ‘Python’
    • >>> my_string

    ‘Python’

    We cannot delete or remove characters from a string. But deleting the string entirely is possible using the del keyword.

    • >>> del my_string[1]

    TypeError: ‘str’ object doesn’t support item deletion

    • >>> del my_string
    • >>> my_string

    NameError: name ‘my_string’ is not defined

    Python String Operations

    There are many operations that can be performed with string which makes it one of the most used data types in Python.

    To learn more about the data types available in Python visit:

    Python Data Types

    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.

    • # Python String Operations
    • str1 = ‘Hello’
    • str2 =’World!’
    • # using +
    • print(‘str1 + str2 = ‘, str1 + str2)
    • # using *
    • print(‘str1 * 3 =’, str1 * 3)

    Run Code

    When we run the above program, we get the following output:

    str1 + str2 =  HelloWorld!

    str1 * 3 = HelloHelloHello

    Writing two string literals together also concatenates them like + operator.

    If we want to concatenate strings in different lines, we can use parentheses.

    • >>> # two string literals together
    • >>> ‘Hello ”World!’

    ‘Hello World!’

    • >>> # using parentheses
    • >>> s = (‘Hello ‘
    • …      ‘World’)
    • >>> s

    ‘Hello World’

    Iterating Through a string

    We can iterate through a string using a for loop. Here is an example to count the number of ‘l’s in a string.

    • # Iterating through a string
    • count = 0
    • for letter in ‘Hello World’:
    •     if(letter == ‘l’):
    •         count += 1
    • print(count,’letters found’)

    Run Code

    When we run the above program, we get the following output:

    3 letters found

    String Membership Test

    We can test if a substring exists within a string or not, using the keyword in.

    • >>> ‘a’ in ‘program’

    True

    • >>> ‘at’ not in ‘battle’

    False

    Built-in functions to Work with Python

    Various built-in functions that work with sequence work with strings as well.

    Some of the commonly used ones are enumerate() and len(). The enumerate() function returns an enumerate object. It contains the index and value of all the items in the string as pairs. This can be useful for iteration.

    Similarly, len() returns the length (number of characters) of the string.

    • str = ‘cold’
    • # enumerate()
    • list_enumerate = list(enumerate(str))
    • print(‘list(enumerate(str) = ‘, list_enumerate)
    • #character count
    • print(‘len(str) = ‘, len(str))

    Run Code

    When we run the above program, we get the following output:

    list(enumerate(str) =  [(0, ‘c’), (1, ‘o’), (2, ‘l’), (3, ‘d’)]

    len(str) =  4

    Python String Formatting

    Escape Sequence

    If we want to print a text like He said, “What’s there?”, we can neither use single quotes nor double quotes. This will result in a SyntaxError as the text itself contains both single and double quotes.

    • >>> print(“He said, “What’s there?””)

    SyntaxError: invalid syntax

    • >>> print(‘He said, “What’s there?”‘)

    SyntaxError: invalid syntax

    One way to get around this problem is to use triple quotes. Alternatively, we can use escape sequences.

    An escape sequence starts with a backslash and is interpreted differently. If we use a single quote to represent a string, all the single quotes inside the string must be escaped. Similar is the case with double quotes. Here is how it can be done to represent the above text.

    • # using triple quotes
    • print(”’He said, “What’s there?””’)
    • # escaping single quotes
    • print(‘He said, “What\’s there?”‘)
    • # escaping double quotes
    • print(“He said, \”What’s there?\””)

    Run Code

    When we run the above program, we get the following output:

    He said, “What’s there?”

    He said, “What’s there?”

    He said, “What’s there?”

    Here is a list of all the escape sequences supported by Python.

    Escape Sequence Description

    \newline Backslash and newline ignored

    \\ Backslash

    \’ Single quote

    \” Double quote

    \a ASCII Bell

    \b ASCII Backspace

    \f ASCII Formfeed

    \n ASCII Linefeed

    \r ASCII Carriage Return

    \t ASCII Horizontal Tab

    \v ASCII Vertical Tab

    \ooo Character with octal value ooo

    \xHH Character with hexadecimal value HH

    Here are some examples:

    Course Curriculum

    Enroll in Best Python Training and Get Hired by TOP MNCs

    • Instructor-led Sessions
    • Real-life Case Studies
    • Assignments
    Explore Curriculum

    • >>> print(“C:\\Python32\\Lib”)

    C:\Python32\Lib

    • >>> print(“This is printed\nin two lines”)

    This is printed in two lines.

    • >>> print(“This is \x48\x45\x58 representation”)

    This is HEX representation

    Raw String to ignore escape sequence.

    Sometimes we may wish to ignore the escape sequences inside a string. To do this we can place r or R in front of the string. This will imply that it is a raw string and any escape sequence inside it will be ignored.

    • >>> print(“This is \x61 \ngood example”)

    This is a good example

    • >>> print(r”This is \x61 \ngood example”)

    This is \x61 \ngood example

    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 which get replaced.

    We can use positional arguments or keyword arguments to specify the order.

    • # Python string format() method
    • # default(implicit) order
    • default_order = “{}, {} and {}”.format(‘John’,’Bill’,’Sean’)
    • print(‘\n— Default Order —‘)
    • print(default_order)
    • # order using positional argument
    • positional_order = “{1}, {0} and {2}”.format(‘John’,’Bill’,’Sean’)
    • print(‘\n— Positional Order —‘)
    • print(positional_order)
    • # order using keyword argument
    • keyword_order = “{s}, {b} and {j}”.format(j=’John’,b=’Bill’,s=’Sean’)
    • print(‘\n— Keyword Order —‘)
    • print(keyword_order)

    Run Code

    When we run the above program, we get the following output:

    Default Order : John, Bill and Sean

    Positional Order : Bill, John and Sean

    Keyword Order : Sean, Bill and John

    The format() method can have optional format specifications. They are separated from the field name using colon. For example, we can left-justify <, right-justify > or center ^ a string in the given space.

    We can also format integers as binary, hexadecimal, etc. and floats can be rounded or displayed in the exponent format. There are tons of formatting you can use. Visit here for all the string formatting available with the format() method.

    • >>> # formatting integers
    • >>> “Binary representation of {0} is {0:b}”.format(12)

    ‘Binary representation of 12 is 1100’

    • >>> # formatting floats
    • >>> “Exponent representation: {0:e}”.format(1566.345)

    ‘Exponent representation: 1.566345e+03’

    • >>> # round off
    • >>> “One third is: {0:.3f}”.format(1/3)

    ‘One third is: 0.333’

    • >>> # string alignment
    • >>> “|{:<10}|{:^10}|{:>10}|”.format(‘butter’,’bread’,’ham’)

    ‘|butter    |  bread   |       ham|’

    Advantages of Python:

    Let’s see how Python dominates over other languages.

    Course Curriculum

    Get Experts Curated Python Training Course to Biuld Your Skills & Career

    Weekday / Weekend BatchesSee Batch Details

    • Extensive Libraries: Python downloads with an extensive library and it contain code for various purposes like regular expressions, documentation-generation, unit-testing, web browsers, threading, databases, CGI, email, image manipulation, and more. So, we don’t have to write the complete code for that manually.
    • Extensible: As we have seen earlier, Python can be extended to other languages. You can write some of your code in languages like C++ or C. This comes in handy, especially in projects.
    • Embeddable: Complimentary to extensibility, Python is embeddable as well. You can put your Python code in your source code of a different language, like C++. This lets us add scripting capabilities to our code in the other language.
    • Improved Productivity: The language’s simplicity and extensive libraries render programmers more productive than languages like Java and C++ do. Also, the fact that you need to write less and get more things done.
    • IOT Opportunities: Since Python forms the basis of new platforms like Raspberry Pi, it finds the future bright for the Internet Of Things. This is a way to connect the language with the real world.
    • Simple and Easy: When working with Java, you may have to create a class to print ‘Hello World’. But in Python, just a print statement will do. It is also quite easy to learn, understand, and code. This is why when people pick up Python, they have a hard time adjusting to other more verbose languages like Java.
    • Readable: Because it is not such a verbose language, reading Python is much like reading English. This is the reason why it is so easy to learn, understand, and code. It also does not need curly braces to define blocks, and indentation is mandatory. This further aids the readability of the code.
    • Object-Oriented: This language supports both the procedural and object-oriented programming paradigms. While functions help us with code reusability, classes and objects let us model the real world. A class allows the encapsulation of data and functions into one.
    • Free and Open-Source: Like we said earlier, Python is freely available. But not only can you download Python for free, but you can also download its source code, make changes to it, and even distribute it. It downloads with an extensive collection of libraries to help you with your tasks.
    • Portable: When you code your project in a language like C++, you may need to make some changes to it if you want to run it on another platform. But it isn’t the same with Python. Here, you need to code only once, and you can run it anywhere. This is called Write Once Run Anywhere (WORA). However, you need to be careful enough not to include any system-dependent features.
    • Interpreted: Lastly, we will say that it is an interpreted language. Since statements are executed one by one, debugging is easier than in compiled languages.

    Advantages of Python Over Other Languages:

    • Less Coding: Almost all of the tasks done in Python requires less coding when the same task is done in other languages. Python also has an awesome standard library support, so you don’t have to search for any third-party libraries to get your job done. This is the reason that many people suggest learning Python to beginners.
    • Affordable: Python is free therefore individuals, small companies or big organizations can leverage the free available resources to build applications. Python is popular and widely used so it gives you better community support. The 2019 Github annual survey showed us that Python has overtaken Java in the most popular programming language category.
    • Python is for Everyone: Python code can run on any machine whether it is Linux, Mac or Windows. Programmers need to learn different languages for different jobs but with Python, you can professionally build web apps, perform data analysis and machine learning, automate things, do web scraping and also build games and powerful visualizations. It is an all-rounder programming language.

    Disadvantages of Python:

    So far, we’ve seen why Python is a great choice for your project. But if you choose it, you should be aware of its consequences as well. Let’s now see the downsides of choosing Python over another language.

    Python Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download
    • Speed Limitations: We have seen that Python code is executed line by line. But since Python is interpreted, it often results in slow execution. This, however, isn’t a problem unless speed is a focal point for the project. In other words, unless high speed is a requirement, the benefits offered by Python are enough to distract us from its speed limitations.
    • Weak in Mobile Computing and Browsers: While it serves as an excellent server-side language, Python is much rarely seen on the client-side. Besides that, it is rarely ever used to implement smartphone-based applications. One such application is called Carbonnelle. The reason it is not so famous despite the existence of Brython is that it isn’t that secure.
    • Design Restrictions: As you know, Python is dynamically-typed. This means that you don’t need to declare the type of variable while writing the code. It uses duck-typing. But wait, what’s that? Well, it just means that if it looks like a duck, it must be a duck. While this is easy on the programmers during coding, it can raise run-time errors.
    • Underdeveloped Database Access Layers: Compared to more widely used technologies like JDBC (Java DataBase Connectivity) and ODBC (Open DataBase Connectivity), Python’s database access layers are a bit underdeveloped. Consequently, it is less often applied in huge enterprises.
    • Simple: No, we’re not kidding. Python’s simplicity can indeed be a problem. Take my example. I don’t do Java, I’m more of a Python person. To me, its syntax is so simple that the verbosity of Java code seems unnecessary. This was all about the Advantages and Disadvantages of Python Programming Language.


    Are you looking training with Right Jobs?

    Contact Us
    Get Training Quote for Free