【问题标题】:Is there a way to remove extra spaces/formatting from an input?有没有办法从输入中删除多余的空格/格式?
【发布时间】:2021-05-17 21:49:37
【问题描述】:

我对 Python 非常陌生,并且正在编写一些代码来操作方程式。到目前为止,我的代码要求用户输入一个方程。我希望我的代码能够采用“X + 1 = 2”之类的内容并将其转换为“x+1=2”,这样我的其余代码就可以正常工作,无论输入公式的格式如何。

【问题讨论】:

标签: python


【解决方案1】:

要转换为小写并去掉任何空格,请使用 lower 和 replace。

the_input = 'X + 1 = 2'

the_output = the_input.replace(' ', '').lower()

# x+1=2

【讨论】:

  • 不要使用input作为变量,input()是Python内置函数。
  • 如果用户输入数据时按两次空格键怎么办?
  • @MarkMoretto 无关紧要,str.replace(char, replacement)char所有 个实例替换为replacement
【解决方案2】:

一个简单的字符串.replace(old, new) 后跟一个.lower() 就足够了。

"X + 1 = 2".replace(" ", "").lower() # 'x+1=2'
"X + 1   = 2".replace(" ", "").lower() # 'x+1=2'

要更彻底地替换所有空白字符而不仅仅是空格,请使用 python 的 re 模块:

import re 

re.sub(r'\s+', '', "X + 1   = 2").lower() # 'x+1=2'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-20
    • 2016-05-19
    相关资源
    最近更新 更多