You can learn about Strings in Python Programs with Outputs helped you to understand the language better.

Python Programming – String

A string is a sequence of one or more characters (letters, numbers, symbols) that can be either a constant or a variable. Strings are the form of data used in programming for storing and manipulating text, such as words, names, and sentences. They are immutable data types, i.e., they are unchanging. You can write them in Python using single quotes, double quotes, or triple quotes. The quotes are not part of the string. They only tell the computer where the string constant begins and ends. String literals are written by enclosing a sequence of characters in single quotes (‘hello’), double quotes (“hello”) or triple quotes (‘”hello”‘ or “””hello”””). Strings are objects of Python’s built-in class ‘str’.

  • A string value is a collection of one or more charac¬ters put in single, double, or triple quotes.

Creating String

To create a string, put the sequence of characters inside single quotes, double quotes, or triple quotes and then assign it to a variable. The single quotes and double quotes work in the same manner for the string creation. Triple quotes can be used in Python to represent multiline strings and docstrings. To store a string inside a variable, you simply need to assign a string to a variable (see Figure 6.1 and Figure 6.2). The following examples show different ways to initialize strings:

Example
Different ways of string initialization.

# Python string examples – all assignments are identical
my_str1 = ‘This is a string in single quotes ‘
my_str2 = ” This is a string in double quotes ”
my_str3 = ” ” ” This is a string in triple quotes ” ” “# With triple quotes strings can extend to multiple lines
String_var = ” ” ” This section will help you to explore all the concepts of Python Strings ” ” “

Python Programming – String chapter 6 img 1

Single Quotes
You can write strings using single quotes, such as ‘This is a string in single quotes.’. They can have any character or sign, including space in them.

Double Quotes
Strings in double-quotes work in the same manner as strings in single quotes. For example, “This is a string in double-quotes.”, “What’s the time now?” etc.\

Triple Quotes
You can write multi-line strings using triple quotes (” ” “). You can also use single quotes and double quotes within the triple quotes. For example, ”’This is a multi-line string. This is the first line.
This is the second line. “What’s the time now?”, I asked.
He said, “It’s quarter to three.”
///

Docstrings
Python has a feature called documentation strings, usually referred to by its short name, docstrings. Docstring is an important tool that helps document the program better and makes it easier to understand.

Leave a Reply

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