Python不将str转换为int。

huangapple go评论62阅读模式
英文:

Python not converting str to int

问题

我编写了这段代码来转换日期

```python
while True: 
    d = input("日期:")
    if "/" in d:
        try:
            x, y, z = d.split("/")
            float(x)
            int(y)
            int(z)
            print(type(x))
            print(type(y))
            print(type(z))
        # print(f" {z : 03d} ")
        # print(f" {x : 03d} ")
        # print(f" {y : 03d} ")
            break
        except:
            break
    if "," in d:
        x, y = d.split(",")
        print(x, y)

但当我输入:

日期:9/8/2020

它没有将字符串转换为整数,输出结果为:
<class 'str'>
<class 'str'>
<class 'str'>

为什么??

预期的类别应该是整数。


<details>
<summary>英文:</summary>

i made this code to convert dates:

while True:
d = input("Date: ")
if "/" in d:
try:
x, y, z = d.split("/")
float(x)
int(y)
int(z)
print(type(x))
print(type(y))
print(type(z))
# print(f" {z : 03d} ")
# print(f" {x : 03d} ")
# print(f" {y : 03d} ")
break
except:
break
if "," in d:
x, y = d.split(",")
print(x,y)


but when i give an input of:

`Date: 9/8/2020`

it is not converting the strings to ints, output is:
`&lt;class &#39;str&#39;&gt;`
`&lt;class &#39;str&#39;&gt;`
`&lt;class &#39;str&#39;&gt;`

WHY??

expecting the class type to be int 

</details>


# 答案1
**得分**: 2

将以下代码从英文翻译成中文:

```python
x = float(x)
y = int(y)
z = int(z)

没有赋值语句的话,它只是评估表达式然后丢弃结果。

英文:

Change:

float(x)
int(y)
int(z)

to:

x = float(x)
y = int(y)
z = int(z)

Without the assignments, all it's doing is evaluating the expressions, then discarding the results.

答案2

得分: 0

Here is the translated code snippet:

while True:
    d = input("日期:")
    if "/" in d:
        try:
            x, y, z = d.split("/")
            x = float(x)
            y = int(y)
            z = int(z)
            print(type(x))
            print(type(y))
            print(type(z))
            break
        except:
            break
    if "," in d:
        x, y = d.split(",")
        print(x, y)

I have translated the code while preserving the original structure and comments.

英文:
while True: 
    d = input(&quot;Date: &quot;)
    if &quot;/&quot; in d:
        try:
            x, y, z = d.split(&quot;/&quot;)
            x = float(x)
            y = int(y)
            z = int(z)
            print(type(x))
            print(type(y))
            print(type(z))
        # print(f&quot; {z : 03d} &quot;)
        # print(f&quot; {x : 03d} &quot;)
        # print(f&quot; {y : 03d} &quot;)
            break
        except:
            break
    if &quot;,&quot; in d:
        x, y = d.split(&quot;,&quot;)
        print(x,y)

you are just converting not assigning it in to the variable

huangapple
  • 本文由 发表于 2023年6月29日 18:50:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76580337.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定