6 - 檢測一個字符串是否可以轉換爲數字

1. 如何檢測字符串是否爲數字(數字和字母的混合形式)

s1 = '12345'
print('是數字: ', s1.isdigit())

print(int(s1))
是數字:  True
12345
s2 = '12345a'
print('12345a是數字:', s2.isdigit())
print('12345a是字母數字混合形式:', s2.isalnum()) 
12345a是數字: False
12345a是字母數字混合形式: True
s3 = '12_345a'
print('12_345a是字母數字混合形式:', s3.isalnum())

print(' '.isspace())
# 檢測字符串是否爲整數
print('12.45'.isdecimal())
# 檢測字符串是否爲字符
print('abcd3'.isalpha())
12_345a是字母數字混合形式: False
True
False
False

2. 怎樣將一個字符串轉換爲數字才安全

s1 = '1234'
print(int(s1))

s2 = 'a1234'
# 拋出異常
# print(int(s2))

if s2.isdigit():
    print(int(s2))
else:
    print('s2 不是數字,無法轉換')
    
try:
    print(int('222aaa'))
except Exception as e:
    print('222aaa 不是數字,無法轉換')
    print(e)
1234
s2 不是數字,無法轉換
222aaa 不是數字,無法轉換
invalid literal for int() with base 10: '222aaa'
  • 檢測字符串是否爲數字:isdigit
  • 檢測字符串是否爲數字和字母混合:isalnum

7 - 如何反轉字符串

發佈了128 篇原創文章 · 獲贊 128 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章