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

Jak zamienić wielokrotne wystąpienia znaku na końcu stringa?
adams0
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 333
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ć?

stivens
  • Rejestracja: dni
  • Ostatnio: dni
8

mozna regexem po prostu:

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

albo rstrip

Kopiuj
"abc#abc#abc####".rstrip("#")
dvch
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 2
1
Kopiuj
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:

Kopiuj
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.

H4
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 8
0

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

poniższy Listing można skrócić

Kopiuj
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:

Kopiuj
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}')
H4
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 8
0

imitacja rstrip()

Kopiuj
class RemoveLastCharacter:
    def __init__(self, cord, chars=None):
        self.cord = cord
        self.chars = chars

    def delete_chars(self):
        if self.chars is None:
            self.chars = " "
        else:
            self.chars = tuple(self.chars)
        
        while self.cord.endswith(self.chars):
            self.cord = self.cord[:-1]
        return self.cord

# Przykład użycia:
item1 = RemoveLastCharacter("Last#Hashes#to#be#deleted#######", "#")
result1 = item1.delete_chars()
print(result1)  # Wyświetli: "Last#Hashes#to#be#deleted"

item2 = RemoveLastCharacter("You are number 1 777666555888", "8675")
result2 = item2.delete_chars()
print(result2)  # Wyświetli: "You are number 1"

item3 = RemoveLastCharacter("apple       ") # brak drugiego argumentu, usuwa domyślnie sapcje
result3 = item3.delete_chars()
print(f"of all fruits, {result3} is my favorite") 

Zarejestruj się i dołącz do największej społeczności programistów w Polsce.

Otrzymaj wsparcie, dziel się wiedzą i rozwijaj swoje umiejętności z najlepszymi.