복붙노트

[PYTHON] 파이썬에서 주어진 문자열에 주어진 문자열에 문자열을 삽입하십시오.

PYTHON

파이썬에서 주어진 문자열에 주어진 문자열에 문자열을 삽입하십시오.

파이썬에서 문제가있는 초보자입니다. 이미 기존 문자열에 일부 필드를 삽입하는 방법은 무엇입니까?

예를 들어 다음을 포함하는 파일에서 한 줄을 읽었다 고 가정합니다.

line = "Name Age Group Class Profession"

이제 3 번째 필드 (그룹)를 클래스 필드 앞에 같은 줄에 3 번 더 삽입해야합니다. 출력 라인은 다음과 같아야합니다.

output_line = "Name Age Group Group Group Group Class Profession"

쉽게 세 번째 필드를 검색 할 수 있지만 (split 메서드 사용) 문자열에 삽입하는 가장 쉬운 방법을 알려주시겠습니까?

해결법

  1. ==============================

    1.새로운 파이썬 프로그래머에게는 종종 맞지만 다른 포스터에서는 명시 적으로 작성하지 않은 중요한 점은 파이썬의 문자열이 변경되지 않는다는 것입니다.

    새로운 파이썬 프로그래머에게는 종종 맞지만 다른 포스터에서는 명시 적으로 작성하지 않은 중요한 점은 파이썬의 문자열이 변경되지 않는다는 것입니다.

    파이썬에서 문자열로 작업 할 때 "이 문자열을 어떻게 수정할 수 있습니까?"라고 생각하는 대신 자신을 재교육해야합니다. 대신 당신은 "내가 이미 얻은이 조각으로부터 몇 조각을 가진 새로운 문자열을 만들 수 있을까?"라고 생각하고 있습니다.

  2. ==============================

    2.이 문제를 다루는 미래의 '초보자'를 위해서, 나는이 대답에 대한 빠른 답이 맞을 것이라고 생각한다.

    이 문제를 다루는 미래의 '초보자'를 위해서, 나는이 대답에 대한 빠른 답이 맞을 것이라고 생각한다.

    bgporter가 말했듯이, 파이썬 문자열은 변경할 수 없으므로 문자열을 수정하려면 이미 가지고있는 조각을 사용해야합니다.

    다음 예제에서는 'Kong Panda'에 'Fu'를 삽입하여 'Kung Fu Panda'를 만듭니다.

    >>> line = 'Kong Panda'
    >>> index = line.find('Panda')
    >>> output_line = line[:index] + 'Fu ' + line[index:]
    >>> output_line
    'Kong Fu Panda'
    

    위의 예제에서 인덱스 값을 사용하여 문자열을 2 개의 하위 문자열로 '슬라이스'했습니다. 1은 삽입 색인 앞에 하위 문자열을 포함하고 나머지는 나머지를 포함합니다. 그런 다음 두 문자열 사이에 원하는 문자열을 추가하기 만하면 다른 문자열 안에 문자열을 삽입했습니다.

    파이썬의 슬라이스 표기법은 문자열 분할의 주제를 설명하는 훌륭한 대답을 가지고 있습니다.

  3. ==============================

    3.나는 그것이 malapropos 다라는 것을 알고있다. 그러나 IMHO 쉬운 길은 다음과 같다 :

    나는 그것이 malapropos 다라는 것을 알고있다. 그러나 IMHO 쉬운 길은 다음과 같다 :

    def insert (source_str, insert_str, pos):
        return source_str[:pos]+insert_str+source_str[pos:]
    
  4. ==============================

    4.

    line='Name Age Group Class Profession'
    arr = line.split()
    for i in range(3):
        arr.insert(2, arr[2])
    print(' '.join(arr))
    
  5. ==============================

    5.이를 수행하는 방법에는 여러 가지가 있습니다.

    이를 수행하는 방법에는 여러 가지가 있습니다.

    한 가지 방법은 조각을 사용하는 것입니다.

    >>> a="line=Name Age Group Class Profession"
    >>> b=a.split()
    >>> b[2:2]=[b[2]]*3
    >>> b
    ['line=Name', 'Age', 'Group', 'Group', 'Group', 'Group', 'Class', 'Profession']
    >>> a=" ".join(b)
    >>> a
    'line=Name Age Group Group Group Group Class Profession'
    

    또 다른 방법은 정규식을 사용하는 것입니다.

    >>> import re
    >>> a=re.sub(r"(\S+\s+\S+\s+)(\S+\s+)(.*)", r"\1\2\2\2\2\3", a)
    >>> a
    'line=Name Age Group Group Group Group Class Profession'
    
  6. ==============================

    6.나는 DNA 할당과 관련하여 비슷한 문제가 있었고 bgporter의 조언을 사용하여 대답했다. 여기에 새로운 문자열을 만드는 내 함수는 ...

    나는 DNA 할당과 관련하여 비슷한 문제가 있었고 bgporter의 조언을 사용하여 대답했다. 여기에 새로운 문자열을 만드는 내 함수는 ...

    def insert_sequence(str1, str2, int):
        """ (str1, str2, int) -> str
    
        Return the DNA sequence obtained by inserting the 
        second DNA sequence into the first DNA sequence 
        at the given index.
    
        >>> insert_sequence('CCGG', 'AT', 2)
        CCATGG
        >>> insert_sequence('CCGG', 'AT', 3)
        CCGATG
        >>> insert_sequence('CCGG', 'AT', 4)
        CCGGAT
        >>> insert_sequence('CCGG', 'AT', 0)
        ATCCGG
        >>> insert_sequence('CCGGAATTGG', 'AT', 6)
        CCGGAAATTTGG
    
        """
    
        str1_split1 = str1[:int]
        str1_split2 = str1[int:]
        new_string = str1_split1 + str2 + str1_split2
        return new_string
    
  7. ==============================

    7.아래 함수는 하나의 문자열을 다른 문자열에 삽입 할 수있게합니다 :

    아래 함수는 하나의 문자열을 다른 문자열에 삽입 할 수있게합니다 :

    def str_insert(from_me, into_me, at):
        """
        Inserts the string <from_me> into <into_me>
    
        Input <at> must be an integer index of <into_me> or a substring of <into_me>
    
        Inserts <from_me> AFTER <at>, not before <at>
    
        Inputs <from_me> and <into_me> must have working __str__ methods defined.
        This is satisfied if they already are strings.
    
        If not already strings, <from_me>, <into_me> 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 '<at>' 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 <from_me> into <into_me>
    
        Inserts <from_me> AFTER <at>, not before <at>
    
        Input <at> must be an integer index of <into_me> or a substring of <into_me>
    
        If <at> is the string '15', that substring will be searched for,
        '15' will not be interpreted as an index/subscript.        
    
        Inputs <from_me> and <into_me> must have working __str__ methods defined.
        If not already strings, <from_me>, <into_me> 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'
            '<at>'
        """
        try:
            if isinstance(at, int):
                return str_insert_by_int(from_me, into_me, at)
            # Below, the calls to str() work fine if <at> and <from_me> 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 ("<at>" in serr) and 'not found' in serr:
                msg_start = "In " + str_insert_or_raise.__name__ + ":  "
                msg = [msg_start, "\ninput ", "<at> string", " not found in ", "<into_me>",
                                  "\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 <from_me> into <into_me>
    
        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 <from_me> is empty or <at> is not a substring of <into_me> then
        an exception is raised.
    
        For fewer exceptions, use <str_insert_or_raise> 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 <at>, instead of every occurrence of <at>
        if (s == into_me): # <at> string not found and/or <from_me> 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 <at> string not found in <into_me>.",
                                        "\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 <from_me> into <into_me> at integer index <at>    
        * throws exceptions if input arguments are not strings.    
        * Also, throws an  exception if you try to insert the empty string    
        * If <at> is less than zero, <from_me> gets placed at the
          beginning of <into_me>    
        * If <at> is greater than the largest index of <into_me>,
          <from_me> gets placed after the end of <into_me>
    
        For fewer exceptions, use <str_insert_or_raise> instead.
        """
        at = into_me[:(at if at > 0 else 0)]
        return str_insert_by_str(from_me, into_me, at)
    

    아래 코드는 이전에 주어진 str_insert 함수를 호출하는 방법을 보여줍니다.

    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))
    

    위의 함수 중 어느 것도 "in-place"문자열을 수정하지 않습니다. 함수는 각각 문자열의 수정 된 복사본을 반환하지만 원래 문자열은 그대로 유지됩니다.

    예를 들어,

    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
    
  8. ==============================

    8.다른 문자열에있는 문자열의 삽입 위치에 대한 대답

    다른 문자열에있는 문자열의 삽입 위치에 대한 대답

    str1 = "ibuprofen"
    str2 = "MEDICAL"
    final_string=""
    Value = 2
    list2=[]
    result=[str1[i:i+Value] for i in range(0, len(str1), Value)]
    count = 0
    
    for letter in result:
        if count < len(result)-1:
            final_string = letter + str2[count]
            list2.append(final_string)
        elif ((len(result)-1)==count):
            list2.append(letter + str2[count:len(str2)])
            break
        count += 1
    
    print(''.join(list2))
    
  9. from https://stackoverflow.com/questions/4022827/insert-some-string-into-given-string-at-given-index-in-python by cc-by-sa and MIT license