0

我正在阅读 python 速成课程书。作者谈到了剥离空白,以及如何在字符串中消除它们:

他举了一个这样的例子:

favorite_language='python '
print(favorite_language.rstrip())

-- 'python'

您可以看到空白消失了。每当我在 sublime 中尝试它时,它都会给我第一个'python '带有额外空格的字符串 ( )。

4

1 回答 1

0

rstrip():返回一个删除了尾随空格的新字符串。从字符串的“右侧”删除空格更容易记住。

请访问此站点以了解有关 python 中的格式化字符串。

#!/usr/bin/env python3.10
favorite_language=' python language '

print("."+favorite_language.rstrip()+".")#removes trailing white spaces
print("."+favorite_language.strip()+".")#removes white spaces from both leading and trailing
print("."+favorite_language.lstrip()+".")#removes ending white spaces

输出:

$ python3.10 myClass.py 
. python language.
.python language.
.python language .
于 2022-02-12T01:05:36.900 回答