python 中的 Isspace 函数

Isspace function in python

我在尝试执行此代码时遇到问题,我希望用户输入一个值,程序会检查该值是否为字符串,然后检查它的 returns 长度。 如果该值包含空格,程序将删除空格并打印长度。 但如果它包含任何整数值,程序 returns "No Integers is Allowed"

这是代码:

def length(Name):
    long = len(Name)
    return long

new_length = input("Please Enter Your name You can use Spaces: ")
value1 = new_length
if value1.isspace() == True:
  print("This is Before Removing Spaces: " + value1)
  value2 = value1.replace(" ", "")
  print("This is After Removing Spaces: " + value2)
elif value1.isalpha() == True: 
  print("Here is The Length: ", length(value1))
elif value1.isdigit() == True:
    print("Integers are not allowed! ")
else:
    print("There's someting wrong with  "+ value1)

因此,如果您能帮助我,我将不胜感激。 谢谢

您可以使用此函数检查输入字符串是否包含数字:

def hasNumbers(inputString):
        return any(char.isdigit() for char in inputString)

returns有数字则为真,无则为假

至于空格,您可以省略 isspace()。单独使用 replace() 就可以完成这项工作,即使没有空格也是如此。

stri='jshsb sjhsvs jwjjs'
stri=stri.replace(' ','')

您可以使用 Python 中的 re 模块来检查字符串中的空格。 returns 如果有空格则为 True,否则为 False。

import re
def length(Name):
    long = len(Name)
    return long

new_length = input("Please Enter Your name You can use Spaces: ")
value1 = new_length
if re.search('\s', value1):
  print("This is Before Removing Spaces: " + value1)
  value2 = value1.replace(" ", "")
  print("This is After Removing Spaces: " + value2)
  print("Here is The Length: ", length(value2))
elif value1.isalpha() == True: 
  print("Here is The Length: ", length(value1))
elif value1.isdigit() == True:
    print("Integers are not allowed! ")
else:
    print("There's someting wrong with  "+ value1)

我不认为 str.isspacestr.isalphastr.isdigit 方法可以达到您期望的效果。首先,它们都会测试 所有 您输入的字符串中的字符是否属于它们名称中描述的类型。如果 any 个字符匹配,您的代码似乎期望它们是 return True。也就是说,如果有 any 个空格,你想删除它们并显示前后两个长度。

在 Python 中没有可以为您进行该测试的单一字符串方法。您可以使用正则表达式(功能更强大,但 much 更复杂),或者您可以编写一些稍微更复杂的代码来进行测试。我建议使用 any 函数,并向它传递一个生成器表达式,该表达式调用字符串中每个字符所需的方法。

if any(c.isspace() for c in user_str):
    ...

这可能不是您想要的所有测试。您的代码所需的逻辑并不十分明显,因为您的输出没有专门解决许多极端情况。包含字母和数字的字符串有效吗?数字之间有空格但根本没有字母的数字怎么样?您可能需要重新排列 if/elif/else 语句的条件,以便它们符合您的意图。

我还注意到您用于用户输入的变量名称 new_length 非常具有误导性。这不是长度,它是您要测量长度的字符串!具有误导性或不清楚变量名的变量更容易出现逻辑错误,因此花点时间回过头来重新考虑您之前选择的名称有时是个好主意,因为它可以大大提高代码的清晰度!描述性变量名很好,但它是清晰度和简洁性之间的权衡,因为长名称输入起来很乏味(并且容易出现拼写错误)。它们还可能导致行长问题,这会降低在编辑器屏幕上一次查看所有代码的便利性。

我建议阅读这些情况下的文档。对于 isspace,注意 here

Return True if there are only whitespace characters in the string and there is at least one character, False otherwise.

也就是说,如果那里有任何不是 space 的东西,它将是 False。这很烦人,但为什么要首先检查呢?只做更换!如果没有whitespace,它什么都不做。如果您需要打印这些语句,您可以

if ' ' in value1:
  ...

(当然,这并没有考虑所有可能的白色spaces,如果需要,请检查其他答案以执行for循环)

接下来,我认为您需要删除 elif 并只使用 if 语句,因为请注意,如果您输入带有 space 的名称,它将打印删除了 spaces 的名称...之后什么都没有。即使它里面有整数也不行。这是因为 elif 语句不会在它们上面执行一次。

还有很多其他的事情你需要考虑,但我认为你应该首先考虑这两个。希望有用!