【python】列表中数字的元素变整型,其他元素保持原有数据型


把字符串"File1 alias File2 45332"变成列表,但是转换之后所有元素都变成字符串型了,把数字“45332”变成整型,但不影响其他元素。

#自定义判断是否为整型的函数
def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass
 
    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass
 
    return False

listCmd = "File1 alias File2 45332"
#把字符串转换成列表
listCmd = listCmd.split()

for i in range(len(listCmd)):
    #如果是整型的话就进行转换
    if is_number(listCmd[i]):
        listCmd[i] = int(listCmd[i])

print(listCmd)

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM