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ć?
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ć?
mozna regexem po prostu:
import re
re.sub("#+$", "", "abc#abc#abc####")
albo rstrip
"abc#abc#abc####".rstrip("#")
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.
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}')
imitacja rstrip()
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")