简体   繁体   English

使用int()将字符串转换为int时出错

[英]Error converting string to int with int()

I'm using Flask to write a very basic API. 我正在使用Flask编写非常基本的API。 All it should do is get the string from the URI, convert it to an integer, multiply it by 1000 to go from seconds to milliseconds, add it to the current time in milliseconds, and parse the output in time format. 它要做的就是从URI中获取字符串,将其转换为整数,将其乘以1000,从秒到毫秒,将其添加到当前时间(以毫秒为单位),然后以时间格式解析输出。

Here is the code I have so far for converting seconds to milliseconds: 这是到目前为止我将秒转换为毫秒的代码:

from flask import Flask, request, url_for

@app.route('/api/<seconds>')
    def api_seconds(seconds):
    milliseconds = int(seconds) * 1000
    return 'Seconds: ' + seconds + '\n' + 'Milliseconds: ' + milliseconds

This returns an Internal Server Error. 这将返回内部服务器错误。 When I remove the milliseconds variable completely and just use seconds, it works fine. 当我完全删除毫秒变量并仅使用秒时,它工作正常。 According to the Flask page, @app.route('api/<int:seconds>') should return the string as an integer and I could just omit the int(seconds) . 根据Flask页面, @app.route('api/<int:seconds>')应该以整数形式返回字符串,而我可以省略int(seconds) However, this also returns an Internal Server Error. 但是,这也会返回内部服务器错误。

Also, '\\n' isn't creating a new line for me. 另外, '\\n'不会为我创建新行。

You can't concatenate strings with integers. 您不能将字符串与整数连接。 Convert the integer to a string before concatenation. 连接前将整数转换为字符串。

return 'Seconds: ' + seconds + '\n' + 'Milliseconds: ' + str(milliseconds)
                                                         ^

Alternatively, you can use string formatting, which takes care of that for you: 另外,您可以使用字符串格式,该格式将为您解决:

return 'Seconds: {}\nMilliseconds: {}'.format(seconds, milliseconds)

Since you're working with the Flask framework and will be displaying this as HTML in a browser, you'll need to use an appropriate line break like <br /> : 由于您正在使用Flask框架,并将在浏览器中将其显示为HTML,因此您需要使用适当的换行符,例如<br />

return 'Seconds: {}<br />Milliseconds: {}'.format(seconds, milliseconds)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM