Jak usunąć początkowe białe znaki w Pythonie?
Mam ciąg tekstowy, który zaczyna się od wielu spacji, różniących się między 2 i 4.
Jaki jest najprostszy sposób na usunięcie wiodących białych znaków? (tj. usunąć wszystko przed określoną postacią?)
" Example" -> "Example"
" Example " -> "Example "
" Example" -> "Example"
5 answers
The lstrip()
metoda usunie początkowe spacje, znaki nowej linii i tabulacji na początku łańcucha znaków:
>>> ' hello world!'.lstrip()
'hello world!'
Edit
Jak zauważył balpha w komentarzach , aby usunąć tylko spacje z początku łańcucha, należy użyć lstrip(' ')
:
>>> ' hello world with 2 spaces and a tab!'.lstrip(' ')
'\thello world with 2 spaces and a tab!'
Podobne pytanie:
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-27 22:40:00
Funkcja strip
usunie białe znaki z początku i końca łańcucha.
my_str = " text "
my_str = my_str.strip()
Ustawia my_str
na "text"
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-13 13:59:58
Jeśli chcesz wyciąć białe spacje przed i za słowem, ale zachowaj środkowe.
Możesz użyć:
word = ' Hello World '
stripped = word.strip()
print(stripped)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-14 11:07:52
Aby usunąć wszystko przed określonym znakiem, użyj wyrażenia regularnego:
re.sub(r'^[^a]*', '')
Aby usunąć wszystko do pierwszego "a". [^a]
można zastąpić dowolną klasą znaków, np. znakami słownymi.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-06-06 08:04:13
Pytanie nie dotyczy ciągów wielowierszowych, ale oto jak można usunąć wiodące spacje z wielowierszowego ciągu za pomocą standardowej biblioteki Pythona moduł texttwrap. Gdybyśmy mieli taki ciąg jak:
s = """
line 1 has 4 leading spaces
line 2 has 4 leading spaces
line 3 has 4 leading spaces
"""
Jeśli print(s)
otrzymamy wyjście takie jak:
>>> print(s)
this has 4 leading spaces 1
this has 4 leading spaces 2
this has 4 leading spaces 3
I jeśli użyliśmy textwrap.dedent
:
>>> import textwrap
>>> print(textwrap.dedent(s))
this has 4 leading spaces 1
this has 4 leading spaces 2
this has 4 leading spaces 3
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-08-12 21:46:27