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

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

WBOY
WBOYforward
2023-04-21 14:28:071282browse

    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"

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

    message = "It's a string"

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

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

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

    message = 'It\'s also a valid string'

    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'

    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)

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

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

    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'

    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)

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

    Hi jianguo

    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)

    Output:

    Good Morning!

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

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

    Output:

    Good Afternoon!

    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

    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

    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

    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)

    Output:

    13

    Slicing a string

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

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

    Output:

    Py

    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]

    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'

    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>

    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)

    Output:

    Jython String

    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!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete