Python怎样去除字符串中的空格

最近更新时间 2020-02-29 14:37:28

在程序中,额外的空白可能令人迷惑。对程序员来说,'python'和'python '看起来几乎没什么两样,但对程序来说,它们却是两个不同的字符串。

空白很重要,因为你经常需要比较两个字符串是否相同。例如,一个重要的示例是,在用户登录网站时检查其用户名。但在一些简单得多的情形下,额外的空格也可能令人迷 惑。所幸在Python中,删除用户输入的数据中的多余的空白易如反掌。

1. 使用 strip 去除左右两边的空格

strip 函数移除字符串头尾指定的字符生成的新字符串,如下所示:

username = ' name '
username = username.strip()
print(username, 'len:', len(username))
name len: 4

2. 使用 lstrip 去除字符串左边的空格

lstrip 函数移除字符串左边的空格,如下所示:

username = ' name '
username = username.lstrip()
print(username, 'len:', len(username))
name  len: 5

3. 使用 rstrip 去除字符串右边的空格

rstrip 函数移除字符串右边的空格,如下所示:

username = ' name '
username = username.rstrip()
print(username, 'len:', len(username))
 name len: 5

 4. 使用 replace 方法替换空格

replace 函数可以替换字符串中的空格,replace 会替换字符串中的空格,如下所示:

username = ' na me '
username = username.replace(' ', '')
print(username, 'len:', len(username))
name len: 4

 5. 使用 split 和 join 方法替换空格

split 函数可以根据空格拆分字符串为数组,join 函数把数组合并为字符串,如下所示:

username = ' na  me '
username = ''.join(username.split())
print(username, 'len:', len(username))
name len: 4
rss_feed