Python Strings
Python Strings
Let’s learn about Python Strings in this tutorial with some examples. Python strings are used for representing and manipulating text data. They are identified as a contiguous set of characters represented in quotation marks.
Python Strings
Python Strings are a sequence of characters. In Python, strings can be created by enclosing characters in single (‘…’) , double(“…”), or triple quotes (”’…”’ or “””…”””).
Triple quotes can be used for multi-line strings. Strings can also include escape characters like:
- \n (newline)
- \t (tab)
- \\ (backslash)
- \’ (single quote)
- \” (double quotes)
Examples
Illustration of Python strings with some examples below:
>>>
>>> s = ‘Testing’ # single quotes
>>> s1 = “Docs” # double quotes
>>> s2 = “”” This is a multi-line
… String with three
… lines “””
>>>
>>> print(s2)
This is a multi-line
String with three
lines
>>>
Strings are immutable. Once created, the contents of a string cannot be changed. This means that every modification to a string results in the creation of a new string.
Python supports indexing and slicing, allowing you to access individual characters or substrings. Subsets of strings can be taken using the slice operation ([] and [i]). The index starts at 0 at the beginning of the string. The -1 index points at the end of the string.
A slicing operator [] can be used to extract a character or a range of characters from
the string.
>>> # Python String Slicing
>>> s = “TestingDocs”
>>>
>>> print(s[3:10])
tingDoc
>>>
>>> # Python Tutorials – www.TestingDocs.com
>>>
>>> # Extract a single character
>>> print(s[7])
D
>>> # String index starts with 0
>>> print(s[0])
T
>>>
Python 3 supports Unicode, allowing strings to include characters from various languages and symbols. Strings are a fundamental data type and are widely used in various applications like web development, data analysis, and automation.
—
Python Tutorials
Python Tutorial on this website can be found at:
https://www.testingdocs.com/python-tutorials/
More information on Python is available at the official website: