在 Python 中修剪空白
要从 Python 中的字符串中删除空白字符(空格和制表符),有几个选项可用:
对于两边的空白:
<code class="python">s = " \t example string\t " s = s.strip()</code>
对于右侧的空格:
<code class="python">s = s.rstrip()</code>
对于左侧的空格:
<code class="python">s = s.lstrip()</code>
剥离特定字符:
你可以通过将哪些字符作为参数传递给 strip() 函数来指定要从字符串中删除的字符:
<code class="python">s = s.strip(' \t\n\r')</code>
这将从字符串两侧删除任何空格、制表符、换行符或回车符。
删除字符串中间的空格:
要删除字符串中间的空格,可以使用正则表达式:
<code class="python">import re print(re.sub('[\s+]', '', s))</code>
这将从字符串中删除所有连续的空白字符序列。
以上是以下是一些根据问答格式定制的标题选项: **专注于具体技术:** * **如何在 Python 中修剪空格:strip()、rstrip()、lstrip()** * **去除白粉病的详细内容。更多信息请关注PHP中文网其他相关文章!