如何检测字符串中的浮点数并将其转换为单个字符串

2024-10-02 20:34:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python的新手,我有一个任务要完成,但是我找不到方法来完成,所以我请求您的帮助。这是我的任务:我必须从用户那里获取输入,例如:

stackoverflow1.2312312321abcd42ds43

并附加:
-浮点数到floatList
-“42”变成evenList
-43变成oddList

这就是我的代码:

user_input = input("Please enter the text: ")

代码:

freeText = ""
floatList = []
evenList = []
oddList = []

for i in user_input:
    if i.isdigit():
        i += freeText
    elif i != "":
        floatList.append(i)

Tags: the方法代码用户inputenterplease浮点数
1条回答
网友
1楼 · 发布于 2024-10-02 20:34:51

主要思想是:

  • 逐个字符地检查输入(就像您对for i in ...所做的那样)
  • 在检查输入的同时,构建一个字符串,其中包含到目前为止已读取的数字(current_number)。你知道吗
  • 另外,还有一个布尔变量,用于说明目前读取的数字是否包含小数点(has_decimal_dot)。你知道吗
  • 如果遇到一个数字,只需将它附加到current_number并继续查看下一个字符。你知道吗
  • 如果你遇到一个点,也把它附加到current_number,记住你遇到了一个点。然后,继续看下一个角色。你知道吗
  • 如果最后你遇到一个不是数字也不是点的字符,你就知道你读的数字已经结束了。
    • 然后,如果你遇到一个点,你知道它是一个浮点,所以你把字符串转换成一个浮点,并把它附加到floatlist中。你知道吗
    • 如果没有遇到点,current_number必须是整数,至少如果它的长度大于0。测试模2以知道它是偶数还是奇数。你知道吗
    • 加完号码后,你得准备下一个号码。再次将current_number设置为空字符串,将has_decimal_dot设置为False
  • 不必对字符串中的最后一个数字做特殊处理的技巧是,确保字符串不以数字结尾。例如,添加一个空格。你知道吗
#user_input = input("Please enter the text: ")
user_input = "stackoverflow1.2312312321abcd42ds43"
   # in the beginning, it is easier to test if you don't have to type the input every time
   # when everything is working more or less, we can try with input from the user

floatList = []
evenList = []
oddList = []

user_input += " "  # add a non-digit at the end so we don't have to handle the last number differently

current_number = ""
has_decimal_dot = False
for i in user_input:
    if i.isdigit():
        current_number += i  # append the character to the string
    elif i == ".":
        current_number += i
        has_decimal_dot = True
    else: # not a digit and not a dot
        if has_decimal_dot and len(current_number) > 1: # the nunber has a dot, but is not only a dot
            floatList.append(float(current_number))
        elif len(current_number) > 0:  # we encountered a non-digit, and the number we were building is not empty
            num = int(current_number)
            if num % 2 == 0:
                evenList.append(num)
            else:
                oddList.append(num)
        current_number = ""  # we just handled the number, now prepare for a next one
        has_decimal_dot = False

相关问题 更多 >