Jak zamienić wielokrotne wystąpienia znaku na końcu stringa?

0

Cześć,

Mam stringi typu 'abc#abc####', abc#abc#abc#### abc########

Chciałbym usunąć każdy # jeśli występuje na końcu.
Jak to zrobić?

7

mozna regexem po prostu:

import re
re.sub("#+$", "", "abc#abc#abc####")

albo rstrip

"abc#abc#abc####".rstrip("#")
0
string = 'abc#abc####'
cleaned_string = string.rstrip('#')
print(cleaned_string)  # 'abc#abc'

Jeśli masz listę stringów, możesz zastosować to dla każdego z nich w pętli:

strings = ['abc#abc####', 'abc#abc#abc####', 'abc########']
cleaned_strings = [s.rstrip('#') for s in strings]
print(cleaned_strings)  # ['abc#abc', 'abc#abc#abc', 'abc']

W ten sposób każdy znak # na końcu stringu zostanie usunięty.

0

można też skorzystać z "Slicing Strings"

poniższy Listing można skrócić

def remove_last_hashes(s):
    for _ in range(len(s) - 1):
        if s[-1] == '#':
            s = s[:-1]
        elif s[-1] != '#':
            break
    return s

text = "ac#dc#####################"
print(f'{text}')
result = remove_last_hashes(text)
print(f'{result}')

lub jeszcze prościej:

def remove_hashes(s):
    while s.endswith('#'):
        s = s[:-1]
    return s

text = "abc#abc#########"
print(f'{text}')
result = remove_hashes(text)
print(f'{result}')

1 użytkowników online, w tym zalogowanych: 0, gości: 1