Python Language String: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 72: Line 72:


=Escaped Characters=
=Escaped Characters=
<code>[[Printing to stdout in Python#Overview|print()]]</code> resolves the escaped characters before sending them to <code>stdout</code>.
'\n'
'\n'



Revision as of 19:36, 18 June 2022

Internal

Overview

String are a Python sequence of characters. Strings are immutable, a character within a string cannot be changed in-place once the string object has been instantiated. Python 3 supports the Unicode standard, so Python 3 strings can contain characters from any written language in the world.

Quotes

String literals can be declared using four type of quotes: sigle quotes '...', double quotes "...", triple single quotes '''...''' and triple double quotes """...""".

Single and Double Quotes

s1 = 'abc'
s2 = "xyz"

Declaring string literals bounded by single and double quotes is equivalent. There are two types of quotes to make it possible to create strings that include single and double quotes: a single-quoted string allows specifying double quotes inside and a double-quoted string allows specifying single quotes inside:

s1 = 'the color is "red"'
s2 = "the shape is 'square'"

Three Single and Three Double Quotes

Multi-line string literals can be declared using three single quotes or three double quotes. The leading and training space in such strings will also be preserved. The attempt to declare multi-line string literals bounded by single or double quotes results in SyntaxError exceptions.

s1 = '''
    the color
        is
    "red"
    '''
s2 = """
    the shape
        is
    'square'
    """
print(s1)
print(s2)

The result is:

    the color
        is
    "red"


    the shape
        is
    'square'

F-String

PEP 498

An f-string is a literal string, prefixed with "f", which contains expressions inside branches. The expressions are replaced with their values. Introduced by PEP 498. Any kind of string (single-quote enclosed, double-quote enclosed and triple-quote enclosed) can be an f-string.

name = "long"
print(f'my name is {name}')
print(f"my name is {name}")
print(f"""

   my name is {name}

""")

Indent to the right over 6 spaces:

i = 10
print(f"{i:>6}")

Escaped Characters

print() resolves the escaped characters before sending them to stdout.

'\n'

'\t'

String type()

The function type() applied to a list returns:

<class 'str'>

To check whether an instance is a string:

i = ...
if type(i) is str:
  ...

The [] Operator and String Slices

The [] operator can be used to read strings from the sequence, but not modify the sequence. Because strings are immutable, an attempt to change a character at a specific position in string will throw an TypeError exception:

s = 'abc'
s[0] = 'x'
[...]
TypeError: 'str' object does not support item assignment

TO DEPLETE

Python Language String TODELETE