Hướng dẫn how to insert to a sting in python? - làm thế nào để chèn vào một chuỗi trong python?

Thực hiện

Các hàm bên dưới sẽ cho phép một chuỗi chèn một chuỗi vào một chuỗi khác:

def str_insert(from_me, into_me, at):
    """
    Inserts the string  into 

    Input  must be an integer index of  or a substring of 

    Inserts  AFTER , not before 

    Inputs  and  must have working __str__ methods defined.
    This is satisfied if they already are strings.

    If not already strings, ,  are converted into strings.

    If you try to insert an empty string, that's fine, and the result
    is no different from the original.

    In order to insert 'from_me' after nothing (insert at the beginning of the string) use:
        at = ''  or  at = 0
    """
    try:
        return str_insert_or_raise(from_me, into_me, at)
    except ValueError as err:
        serr = str(err)
        if (str_insert_or_raise.__name__ in serr) and 'not found' in serr and '' in serr:
            # if can't find where to insert stuff, don't bother to insert it
            # use str_insert_or_raise if you want an exception instead
            return into_me
        else:
            raise err

##############################################################

def str_insert_or_raise(from_me, into_me, at):
    """
    Inserts the string  into 

    Inserts  AFTER , not before 

    Input  must be an integer index of  or a substring of 

    If  is the string '15', that substring will be searched for,
    '15' will not be interpreted as an index/subscript.        

    Inputs  and  must have working __str__ methods defined.
    If not already strings, ,  are converted into strings. 

    If you try to insert something, but we cannot find the position where
    you said to insert it, then an exception is thrown guaranteed to at least
    contain the following three substrings:
        str_insert_or_raise.__name__
        'not found'
        ''
    """
    try:
        if isinstance(at, int):
            return str_insert_by_int(from_me, into_me, at)
        # Below, the calls to str() work fine if  and  are already strings
        # it makes them strings if they are not already
        return str_insert_by_str(str(from_me), str(into_me), str(at))
    except ValueError as err:
        serr = str(err)
        if 'empty string' in serr:
            return into_me # We allow insertion of the empty string
        elif ("" in serr) and 'not found' in serr:
            msg_start = "In " + str_insert_or_raise.__name__ + ":  "
            msg = [msg_start, "\ninput ", " string", " not found in ", "",
                              "\ninput <",   str(at)  , "> not found in <", str(into_me), ">"]
            msg = ''.join(msg)
            raise ValueError(msg) from None
        else:
           raise err
#############################################################
def str_insert_by_str(from_me, into_me, at):
    """
    Inserts the string  into 

    puts 'from_me' AFTER 'at', not before 'at'
    For example,
        str_insert_or_raise(at = '2',  from_me = '0', into_me = '123')
    puts the zero after the 2, not before the 2
    The call returns '1203' not '1023'

    Throws exceptions if input arguments are not strings.

    Also, if  is empty or  is not a substring of  then
    an exception is raised.

    For fewer exceptions, use  instead.
    """
    try:
        s = into_me.replace(at, at + from_me, 1)
    except TypeError as terr: # inputs to replace are not strings
        msg_list = ['Inputs to function ', str_insert_by_str.__name__, '() must be strings']
        raise TypeError(''.join(msg_list)) from None
    # At the end of call to replace(), the '1'  indicates we will replace
    # the leftmost occurrence of , instead of every occurrence of 
    if (s == into_me): #  string not found and/or  is the empty string
        msg_start = "In " + str_insert_by_str.__name__ + ":  "
        if from_me == '':
            msg = ''.join([msg_start, "attempted to insert an empty string"])
            raise ValueError(msg) from None
        raise ValueError(msg_start, "Input  string not found in .",
                                    "\nUnable to determine where you want the substring inserted.") from None
    return s
##################################################
def str_insert_by_int(from_me, into_me, at):
    """
    * Inserts the string  into  at integer index     
    * throws exceptions if input arguments are not strings.    
    * Also, throws an  exception if you try to insert the empty string    
    * If  is less than zero,  gets placed at the
      beginning of     
    * If  is greater than the largest index of ,
       gets placed after the end of 

    For fewer exceptions, use  instead.
    """
    at = into_me[:(at if at > 0 else 0)]
    return str_insert_by_str(from_me, into_me, at)

Cách sử dụng

Mã bên dưới trình bày cách gọi hàm str_insert được đưa ra trước đó

def foo(*args):
    return args

F = 'F. '

s = 'Using the string \'John \' to specify where to make the insertion'
result = str_insert(from_me = F, into_me ='John Kennedy', at ='John ')
print(foo('\n\n', s, '\n', result))

s = 'Using an int returned by find(\'Ken\') to specify where to make the insertion'
index = 'John Kennedy'.find('Ken') # returns the position of the first letter of 'Ken', not the last letter
result = str_insert(from_me = F, into_me ='John Kennedy', at = index)
print(foo('\n\n', s, '\n', result))

s = 'Using an int (5) to specify where to make the insertion.'
result = str_insert(from_me = F, into_me ='John Kennedy', at = 5)
print(foo('\n\n', s, '\n', result))

s = "Looking for an 'at' string which does not exist"
result = str_insert(from_me = F, into_me ='John Kennedy', at ='x')
print(foo('\n\n', s, '\n', result))

s = ''.join(["Looking for the empty string.",
             "\nFind one immediately at the beginning of the string"])
result = str_insert(from_me = F, into_me ='John Kennedy', at = '')
print(foo('\n\n', s, '\n', result))

s = "Insert an empty string at index 3. No visible change"
result = str_insert(from_me = '', into_me = 'John Kennedy', at = 3)
print(foo('\n\n', s, '\n', result))    

for index in [-5, -1, 0, 1, 997, 999]:
    s = "index " + str(index)
    result = str_insert(from_me = F, into_me = 'John Kennedy', at = index)
    print(foo('\n\n', s, '\n', result))

Cảnh báo về việc thiếu khả năng sửa đổi tại chỗ

Không có chức năng nào ở trên sẽ sửa đổi một chuỗi "tại chỗ."Các hàm mỗi trả về một bản sao đã sửa đổi của chuỗi, nhưng chuỗi ban đầu vẫn còn nguyên.

Ví dụ,

s = ''.join(["Below is what we get when we forget ",
             "to overwrite the string with the value",
             " returned by str_insert_or_raise:"])

examp_str = 'John Kennedy'
str_insert('John ', F, examp_str)
print(foo('\n\n', s, '\n', examp_str))

# examp_str is still 'John Kennedy' without the F

Tôi có thể chèn vào một python chuỗi không?

Hàm danh sách () được sử dụng để chuyển đổi chuỗi thành danh sách.Hàm Chèn () được sử dụng để chèn chuỗi yêu cầu hoặc tập hợp các ký tự vào chuỗi.The insert() function is used to insert the required string or set of characters into the string.

Bạn có thể sử dụng chèn vào một chuỗi không?

Chèn () được sử dụng để chèn các ký tự trong chuỗi tại vị trí được chỉ định..

Làm thế nào để bạn thêm một ký tự vào một chuỗi?

Người ta có thể sử dụng phương thức lớp StringBuffer là phương thức chèn () để thêm ký tự vào chuỗi tại vị trí đã cho.Phương thức này chèn biểu diễn chuỗi của kiểu dữ liệu đã cho tại vị trí đã cho trong StringBuffer.Cú pháp: str.use the StringBuffer class method namely the insert() method to add character to String at the given position. This method inserts the string representation of given data type at given position in StringBuffer. Syntax: str.