Заменить символ в скобках другим - PullRequest
0 голосов
/ 03 декабря 2018

Мне нужно заменить все вхождения точек, но только если точка находится в парентезе, на что-то другое (например, точку с запятой), используя python:

Ввод: "Hello (This . will be replaced, this one. too)."
Выход:"Hello (This ; will be replaced, this one; too)."

Ответы [ 3 ]

0 голосов
/ 03 декабря 2018

Не самый элегантный способ, но это должно сработать.

def sanitize(string):
    string = string.split("(",1)
    string0 = str(string[0])+"("
    string1 = str(string[1]).split(")",1)
    ending  = str(")"+string1[1])
    middle  = str(string1[0])

    # replace second "" with character you'd like to replace with
    # I.E. middle.replace(".","!")
    middle  = middle.replace(".","").replace(";","")

    stringBackTogether = string0+middle+ending
    return stringBackTogether

a = sanitize("Hello (This . will be replaced, this one. too).")
print(a)
0 голосов
/ 03 декабря 2018

Зацикливание символов в строке, номер дорожки открывающих и закрывающих скобок, заменяйте только если встречается больше открывающих, чем закрывающих скобок.

def replace_inside_parentheses(string, find_string, replace_string):
    bracket_count = 0
    return_string = ""
    for a in string:
        if a == "(":
            bracket_count += 1
        elif a == ")":
            bracket_count -= 1
        if bracket_count > 0:
            return_string += a.replace(find_string, replace_string)
        else:
            return_string += a
    return return_string


my_str = "Hello (This . will be replaced, this one. too, (even this one . inside nested parentheses!))."
print(my_str)
print(replace_inside_parentheses(my_str, ".", ";"))
0 голосов
/ 03 декабря 2018

Предполагая, что скобки сбалансированы и не вложены, вот идея с re.split.

>>> import re
>>> 
>>> s = 'Hello (This . will be replaced, this one. too). This ... not but this (.).'
>>> ''.join(m.replace('.', ';') if m.startswith('(') else m
...:        for m in re.split('(\([^)]+\))', s))
...:        
'Hello (This ; will be replaced, this one; too). This ... not but this (;).'

Основной трюк заключается в том, чтобы обернуть регулярное выражение \([^)]+\) другой парой (), такой, чтобыспички сохраняются.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...