Строковые методы rstrip(), lstrip() и strip() в Python
Python предоставляет три метода, которые можно использовать для удаления пробелов в строковом объекте.
- strip(): возвращает новую строку после удаления любых начальных и конечных пробелов, включая табуляцию (\ t).
- rstrip(): возвращает новую строку с удаленными конечными пробелами. Это проще запомнить как удаление пробелов с «правой» стороны строки.
- lstrip(): возвращает новую строку с удаленными ведущими пробелами или удаляет пробелы с «левой» стороны строки.
Все эти методы не принимают никаких аргументов для удаления пробелов. Если указан символьный аргумент, они удаляют эти символы из строки с начальных и конечных мест.
Давайте посмотрим на простой пример удаления пробелов из строки в Python.
s1 = ' abc ' print(f'String =\'\'') print(f'After Removing Leading Whitespaces String =\'\'') print(f'After Removing Trailing Whitespaces String =\'\'') print(f'After Trimming Whitespaces String =\'\'')
String =' abc ' After Removing Leading Whitespaces String ='abc ' After Removing Trailing Whitespaces String =' abc' After Trimming Whitespaces String ='abc'
Давайте рассмотрим еще несколько примеров со строками, имеющими новую строку и табуляцию.
>>> s1 = ' X\n Y \nZ \t' >>> s1.strip() 'X\n Y \nZ' >>> s1.rstrip() ' X\n Y \nZ' >>> s1.lstrip() 'X\n Y \nZ \t'
strip() vs lstrip() vs rstrip() in Python
What exactly are these methods doing? I expected ‘thist’ for the first case and ‘that’ for the second case. I’m not looking to fix the problem, I just want to understand the functionality. See also How do I remove a substring from the end of a string? if you do want to fix a problem with removing something from the beginning or end of a string (or are trying to close such a duplicate question).
25.1k 11 11 gold badges 143 143 silver badges 144 144 bronze badges
asked Dec 6, 2016 at 8:16
395 7 7 silver badges 20 20 bronze badges
for learning about strip with some example usecases, I suggest have a look at following link dotnetperls.com/strip-python
Dec 6, 2016 at 8:34
5 Answers 5
str. strip ([ chars ])
Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None , the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:
So, strip will try to remove any of the characters listed in chars from both ends as long as it can. That is, the string provided as an argument is considered as a set of characters, not as a substring.
lstrip and rstrip work the same way, except that lstrip only removes characters on the left (at the beginning) and rstrip only removes characters on the right (at the end).
62.6k 11 11 gold badges 103 103 silver badges 155 155 bronze badges
answered Dec 6, 2016 at 8:21
Ahasanul Haque Ahasanul Haque
10.8k 5 5 gold badges 41 41 silver badges 58 58 bronze badges
a = 'thisthat' a.rstrip('hat')
is equivalent to
a = 'thisthat' to_strip = 'hat' while a[-1] in to_strip: a = a[:-1]
62.6k 11 11 gold badges 103 103 silver badges 155 155 bronze badges
answered Dec 6, 2016 at 8:25
11.9k 2 2 gold badges 29 29 silver badges 35 35 bronze badges
the slicing operator’s end is not included, so it should be a = a[:-1] instead
Feb 20, 2022 at 1:08
strip() can remove all combinations of the spcific characters (spaces by default) from the left and right sides of string.
lstrip() can remove all combinations of the spcific characters (spaces by default) from the left sides of string.
rstrip() can remove all combinations of the spcific characters (spaces by default) from the right sides of string.
test = " a b c " print(test) # " a b c " print(test.strip()) # "a b c" print(test.lstrip()) # "a b c " print(test.rstrip()) # " a b c"
test = "abc a b c abc" print(test) # "abc a b c abc" print(test.strip("cab")) # " a b c " print(test.lstrip("cab")) # " a b c abc" print(test.rstrip("cab")) # "abc a b c "
test = "abc a b c abc" print(test) # "abc a b c abc" print(test.strip("c ab")) # "" print(test.lstrip("c ab")) # "" print(test.rstrip("c ab")) # ""
answered Jul 17 at 15:30
Super Kai — Kazuya Ito Super Kai — Kazuya Ito
25.1k 11 11 gold badges 143 143 silver badges 144 144 bronze badges
lstrip , rstrip and strip remove characters from the left, right and both ends of a string respectively. By default they remove whitespace characters (space, tabs, linebreaks, etc)
>>> a = ' string with spaces ' >>> a.strip() 'string with spaces' >>> a.lstrip() 'string with spaces ' >>> a.rstrip() ' string with spaces'
You can use the chars parameter to change the characters it strips.
>>> a = '. string. ' >>> a.strip('.') 'string'
However, based on your question it sounds like you are actually looking for replace
>>> a = 'thisthat' >>> a.replace('hat', '') 'thist' >>> a.replace('this', '') 'that'
answered Dec 6, 2016 at 8:31
510 2 2 gold badges 6 6 silver badges 18 18 bronze badges
@B Rad C No, I’m not looking for replace, I thought when i strip a word from the string it will take that substring and strips it off. I didn’t know it takes chars as long as it can as Ahsanul Haque explained.
Dec 6, 2016 at 8:34
This is how I understand the lstrip and rstrip methods:
#USING RSTRIP a = 'thisthat' print(a.rstrip('hat')) #Begin with t on the right side, is t in 'hat'? Okay, remove it #Next: a, is a in 'hat'? Okay remove it #Next: h, is h in 'hat'? Okay, remove it #Next: t, is t in 'hat'? Okay, remove it #Next: s, is s in 'hat'? No, so, stop. #Output: this #USING LSTRIP b = 'thisthat' print(b.lstrip('this')) #Begin with t on the left side, is t in 'this'? Okay, remove it #Next: h, is h in 'this'? Okay, remove it #Next: i, is i in 'this'? Okay, remove it #Next: s, is s in 'this'? Okay, remove it #Next: t, is t in 'this'? Okay, remove it #Next: h, is h in 'this'? Okay, remove it #Next: a, is a in 'this'? No, so, stop #Ouput: at #Using STRIP c = 'thisthat' print(c.strip("th")) #Begin from both sides and repeat the steps from above; essentially, stripping from both sides. #Using lstrip => isthat #Now, using rstrip => istha #Ouput: istha
62.6k 11 11 gold badges 103 103 silver badges 155 155 bronze badges
answered Jun 15, 2022 at 17:37
Blue-Spartan Blue-Spartan
1 2 2 bronze badges
- python
- string
- character
- difference
- strip
-
Featured on Meta
Linked
Related
Hot Network Questions
Subscribe to RSS
Question feed
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.11.21.1314
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Python string.rstrip()
The rstrip() method returns a copy of the string by removing the trailing characters specified as argument. If the characters argument is not provided, all trailing whitespaces are removed from the string.
Trailing characters are those characters which occur at the end of the string (rightmost part of the string).
Syntax:
str.rstrip(characters)
Parameters:
characters: (optional) A char or string to be removed from the end of the string.
Return Value:
The following examples demonstrates the rstrip() method.
Example: rstrip()
>>> mystr = ' Hello World ' >>> mystr.rstrip() # removes trailing spaces ' Hello World ' >>> mystr = ''' Python is a programming language ''' >>> mystr.rstrip() # removes trailing \n '\nPython is \na programming language' >>> mystr = '----Hello World----' >>> mystr.rstrip('-') # removes trailing - '----Hello World'
You can specify one or more characters as a string to be removed from the string in any order, as shown below.
Example: rstrip()
>>> '#$2Hello World#$2'.rstrip('$2#') '#$2Hello World' >>> 'Hello World#-$2'.rstrip('$2#') 'Hello World#-' >>> 'www.tutorialsteacher.com/'.rstrip('/.') # remove www. 'www.tutorialsteacher.com' >>> 'bcā'.rstrip('ā') # removes Unicode char 'bc'
In the above example, ‘#$2Hello World#$2’.rstrip(‘$2#’) removes trailing chars’$’, ‘2’, or ‘#’ even if appears in any order. However, Hello World#-$2′.rstrip(‘$2#’) removes only trailing ‘$’ and ‘2’, because ‘-‘ is not specified to be removed, so it stops there and consider it as a word.
Python rstrip: как использовать функцию String rstrip () в Python
Python strip () — это встроенная функция, которая возвращает копию строки с удаленными начальными и конечными символами в зависимости от переданного строкового аргумента.
Python rstrip ()
Python String rstrip () — это встроенный метод, который возвращает копию String с удаленными завершающими символами. Функция rstrip () возвращает копию строки, в которой все символы удалены из конца строки и пробелов по умолчанию.
Здесь следует отметить один наиболее важный момент: эти функции не вносят изменений на месте, и, следовательно, эти изменения являются временными.
Если вы хотите внести эти изменения изменения являются постоянными, вам необходимо назначить его другой переменной для хранения измененной строки, потому что она возвращает измененную строку.
Еще одна важная вещь — по умолчанию, и она удаляет пробелы, если вы не упоминаете символ r.
Синтаксис
string.rstrip ([chars])
Параметры
chars (необязательно): Это строка, определяющая набор символов, которые необходимо удалить.
Возвращаемое значение
Функция rstrip () возвращает копию Строка, в которой все символы удалены из конца строки (символы пробела по умолчанию).
Пример
rand_str = 'Harry Potter'print (' Source string: n ', rand_str) # Ведущие whitepsace удалены print (' Stripped strings: ') print (rand_str.rstrip ()) print (rand_str.rstrip (' kl kb ')) print ( rand_str.rstrip ('mj gigi')) website = 'https://facebook.com/'print(website.rstrip('m/.'))
Вывод
Исходная строка: Гарри Поттер Строки с полосами: Гарри Поттер Гарри Поттер Гарри Поттер https://facebook.co
Вы можете видеть, что в первом случае ведущее белое пространство — rem ved from Гарри Поттер.
Затем во втором и третьем случаях он ничего не удалит, потому что символы, указанные в аргументе, не существуют в исходном Строка.
В последнем случае мы удалили символ m из строки URL, поскольку он соответствует исходной строке веб-сайт .
Пример 2
rand_str = "DataFrame" print ("Pandas" + rand_str.rstrip () + "Пример")
Вывод
Пример Pandas DataFrame
Python rstrip vs. strip
Метод Python strip () удаляет как начальные, так и конечные символы и возвращает строку. Хотя метод rstrip () возвращает копию строки, в которой все символы были удалены из конца строки (символы пробела по умолчанию).
Мы можем резюмировать все функции строковой полосы Python следующим образом.
1. strip () : функция Python strip () используется для удаления всех начальных и конечных символов, упомянутых в ее аргументе. Если аргумент chars опущен или None, символы пробела удаляются. Если указано, а не None, символы должны быть строкой; символы в строке будут удалены с обоих концов строки, для которой вызывается этот метод.
2. lstrip () : функция Python lstrip () используется для удаления всех ведущих символов, упомянутых в параметре функции. Если аргумент chars опущен или None, пробельные символы удаляются. Если задано, а не None, символы должны быть строкой; символы в строке будут удалены из начала строки, для которой вызывается метод lstrip ().
3. rstrip (): Функция Python rstrip () используется для удаления всех завершающих символов, упомянутых в параметре функции. Если аргумент chars опущен или None, пробельные символы удаляются. Если задано, а не None , тогда символы должны быть строкой; символы в строке будут удалены из конца строки, в которой вызывается метод rstrip ().
Как удалить завершающую новую строку в Python
Если вы вызываете метод string rstrip (chars) для строки с « n» в качестве символов для создания новой строки, то завершающий символ новой строки удаляется. Назначьте результирующую строку исходной переменной String.
rand_str = "DataFrame n" print (rand_str) data = "Example" print (data) result = rand_str.rstrip () print (result) data = "Example" print (data)
Вывод
DataFrameExampleDataFrameExample
Из вывода , вы можете видеть, что в первом экземпляре символ n выполняется, а пример печатается на следующей строке. Тем не менее, когда мы удалили символ новой строки с помощью функции rstrip (), мы увидим, что новая строка удаляется, и он немедленно печатает пример.
Метод Python rstrip () удаляет все виды завершающие пробелы по умолчанию, а не только одна новая строка, как Perl с chomp.
Кроме того, я бы сказал, что «питоническим» способом получения строк без завершающих символов новой строки является string.splitlines ().
rand_str = "Python nDataFrame nExample n" print (rand_str) splitlines = rand_str.splitlines () print (splitlines)
Вывод
PythonDataFrameExample ['Python', 'DataFrame', 'Example']
Заключение
Канонический способ убрать символы конца строки (EOL) — использовать метод строки rstrip (), удаляющий любые завершающие r или n. Вы можете использовать это для символов EOL Mac, Windows и Unix.. Использование « r n» в качестве параметра для rstrip означает, что он будет вырезать любую завершающую комбинацию « r» или « n». Вот почему он работает во всех этих случаях ОС.
Наконец, пример Python rstrip () окончен.
См. Также
Python f String
Python многострочный String
Python String rindex ()
Python String rsplit ( )
