1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > lstrip和rstrip_Python装饰字符串– rstrip() lstrip() strip()

lstrip和rstrip_Python装饰字符串– rstrip() lstrip() strip()

时间:2024-01-29 14:04:02

相关推荐

lstrip和rstrip_Python装饰字符串– rstrip() lstrip() strip()

lstrip和rstrip

Python provides three methods that can be used to trim whitespaces from the string object.

Python提供了三种方法,可用于从字符串对象中修剪空格。

Python修剪字符串 (Python Trim String)

strip(): returns a new string after removing any leading and trailing whitespaces including tabs (\t).strip():删除任何包含制表符(\ t)的前导和尾随空格后,返回一个新字符串。rstrip(): returns a new string with trailing whitespace removed. It’s easier to remember as removing white spaces from “right” side of the string.rstrip():返回删除了结尾空格的新字符串。 在字符串的“右侧”删除空格时,更容易记住。lstrip(): returns a new string with leading whitespace removed, or removing whitespaces from the “left” side of the string.lstrip():返回一个新字符串,其中删除了前导空格,或者从字符串的“左侧”删除了空格。

All of these methods don’t accept any arguments to remove whitespaces. If a character argument is provided, then they will remove that characters from the string from leading and trailing places.

所有这些方法都不接受任何用于删除空格的参数。 如果提供了字符参数,则它们将从开头和结尾处的字符串中删除该字符。

Let’s look at a simple example of trimming whitespaces from the string in Python.

让我们看一个简单的示例,该示例从Python中的字符串中修剪空格。

s1 = ' abc 'print(f'String =\'{s1}\'')print(f'After Removing Leading Whitespaces String =\'{s1.lstrip()}\'')print(f'After Removing Trailing Whitespaces String =\'{s1.rstrip()}\'')print(f'After Trimming Whitespaces String =\'{s1.strip()}\'')

Output:

输出:

String =' abc 'After Removing Leading Whitespaces String ='abc 'After Removing Trailing Whitespaces String =' abc'After Trimming Whitespaces String ='abc'

Let’s look at some more examples with strings having a new-line and tabs.

我们来看一些带有换行符和制表符的字符串的更多示例。

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

GitHub Repository.GitHub存储库中签出更多Python字符串示例。

翻译自: /23625/python-trim-string-rstrip-lstrip-strip

lstrip和rstrip

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。