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