【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