我无法将字符串类型中的 ' , ' 替换为 ' ' 以将其转换为整数

sha*_*nal 0 python

我以为我可以使用此代码来转换字符串:

str = "3,443"
str.replace(",", "")
int_num = int(str)
Run Code Online (Sandbox Code Playgroud)

但它不起作用并引发ValueError. 我怎样才能转换这个字符串?

Hél*_*ins 10

str.replace不会更改loco 中的字符串。您需要重新分配它。此外,您不应该使用str命名变量。

string = "3,443"
string = string.replace(",", "")
int_num = int(string)
Run Code Online (Sandbox Code Playgroud)


Aks*_*gal 5

使用 str.replace

您没有在str.replace. str.replace 不是就地方法,它返回必须存储回变量的字符串。

更多细节在这里。

另外,尽量不要str用作变量名,因为它会导致调用 str 方法时出现问题

s = "3,443"
s = s.replace(",", "")
int_num = int(s)
int_num
Run Code Online (Sandbox Code Playgroud)
3443
Run Code Online (Sandbox Code Playgroud)

使用 locale.atoi

然而,正确的方法是使用locale. 更多细节在这里

import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')

s = "3,443"
locale.atoi(s)
Run Code Online (Sandbox Code Playgroud)
3443
Run Code Online (Sandbox Code Playgroud)