在Python中,将字母字符串转换为整数可以通过以下几种方法实现:
1. 使用 `int()` 函数:
str_num = '123'
num = int(str_num)
2. 使用列表推导式(list comprehension):
str_list = ['1', '2', '3']
int_list = [int(i) for i in str_list]
3. 使用 `map()` 函数:
str_list = ['1', '2', '3']
int_list = list(map(int, str_list))
4. 自定义函数实现字符串转整型:
def str2Int(s):
s = s.strip()
if len(s) == 0:
return 0
dict_num = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}
dict_flag = {'+':1, '-':-1}
sum_, flag = 0, 1
if s in dict_num:
flag = dict_flag[s]
elif ord(s) >= ord('0') and ord(s) <= ord('9'):
sum_ = sum_ * 10 + (ord(s) - ord('0'))
return sum_ if flag == 1 else -sum_
s = '-000013dd4'
num = str2Int(s)