Home > Backend Development > Python Tutorial > Python strings: common usage and f-string source code analysis

Python strings: common usage and f-string source code analysis

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-04-21 14:28:07
forward
1383 people have browsed it

    Introduction to Python strings

    A string is a series of characters. In Python, anything within quotes is a string. You can use single or double quotes. For example:

    message = 'This is a string in Python'
    message = "This is also a string"
    Copy after login

    If a string contains a single quote, you should put it inside double quotes, like this:

    message = "It's a string"
    Copy after login

    When a string contains double quotes, you can use single quotes Quotes:

    message = '"Beautiful is better than ugly.". Said Tim Peters'
    Copy after login

    To escape quotes, use backslashes (\). For example:

    message = 'It\'s also a valid string'
    Copy after login

    The Python interpreter treats the backslash character () specially. If you don't want it to do this, you can use a raw string by adding r letters before the first quote. For example:

    message = r'C:\python\bin'
    Copy after login

    Create a multi-line string

    To span a multi-line string, you can use triple quotes """…""" or "‘…"’. For example:

    help_message = '''
    Usage: mysql command
        -h hostname     
        -d database name
        -u username
        -p password 
    '''
    
    print(help_message)
    Copy after login

    If you execute the program, it will output the following:

    Usage: mysql command
        -h hostname
        -d database name
        -u username
        -p password
    Copy after login

    Using variables in Python strings with f-strings

    Sometimes, you want to Use the value of a variable in a string.

    For example, you might want the value of the name variable in a message string variable:

    name = 'jianguo'
    = 'Hi'
    Copy after login

    To do this, you put the letters f before the opening quote, and Place braces around the variable name:

    name = 'jianguo'
    message = f'Hi {name}'
    print(message)
    Copy after login

    Python will replace name with the value of variable {name}. The code will display the following on the screen:

    Hi jianguo
    Copy after login

    This message is a format string, or f-string for short. Python introduced f-string in version 3.6.

    Concatenating Python Strings

    When you place string literals side by side, Python automatically concatenates them into a single string. For example:

    greeting = 'Good ' 'Morning!'
    print(greeting)
    Copy after login

    Output:

    Good Morning!
    Copy after login

    To concatenate two string variables, you can use the operator:

    str = "Python String"
    print(str[0]) # P
    print(str[1]) # y
    Copy after login
    Copy after login

    Output:

    Good Afternoon!
    Copy after login

    Access the characters String Elements

    Since a string is a sequence of characters, you can access its elements using an index. The first character in the string has index zero.

    The following example shows how to access an element using an index:

    str = "Python String"
    print(str[0]) # P
    print(str[1]) # y
    Copy after login
    Copy after login

    How this works:

    First, create a variable that contains the string "Python String". []Then, use square brackets and indexing to access the first and second characters of the string.

    If you use negative indexing, Python will return characters starting from the end of the string. For example:

    str = "Python String"
    print(str[-1])  # g
    print(str[-2])  # n
    Copy after login

    The following explains the index of the string"Python String":

    +---+---+---+---+---+---+---+---+---+---+---+---+---+
    | P | y | t | h | o | n |   | S | t | r | i | n | g | 
    +---+---+---+---+---+---+---+---+---+---+---+---+---+
      0   1   2   3   4   5   6   7   8   9   10  11  12
    -13  -12  -11  -10 -9  -8  -7  -6  -5  -4  -3  -2  -1
    Copy after login

    Get the length of the string

    To get the length of the string Length, you can use the len() function. For example:

    str = "Python String"
    str_len = len(str)
    print(str_len)
    Copy after login

    Output:

    13
    Copy after login

    Slicing a string

    Slicing allows you to get substrings from a string. For example:

    str = "Python String"
    print(str[0:2])
    Copy after login

    Output:

    Py
    Copy after login

    str[0:2] Returns a substring containing from index 0 (inclusive) to 2 (excluded) character.

    The syntax for slicing is as follows:

    string[start:end]
    Copy after login

    The substring always contains the characters located at start and excludes the characters located at end.

    start and end are optional. If start is omitted, it defaults to zero. If end is omitted, it defaults to the length of the string.

    Python strings are immutable

    Python strings are immutable. This means you cannot change the string. For example, if you update one or more characters in a string, you will receive the error message:

    str = "Python String"
    str[0] = 'J'
    Copy after login

    Error:

    Traceback (most recent call last):
      File "app.py", line 2, in <module>
        str[0] = &#39;J&#39;
    TypeError: &#39;str&#39; object does not support item assignment</module>
    Copy after login

    When you want to modify a string, you need to start from the current Create a new string from a string. For example:

    str = "Python String"
    new_str = &#39;J&#39; + str[1:]
    print(new_str)
    Copy after login

    Output:

    Jython String
    Copy after login

    The above is the detailed content of Python strings: common usage and f-string source code analysis. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template