1. 使用内置的`int()`函数:
```python
num_str = "123"
num_int = int(num_str)
print(num_int) 输出:123
2. 使用内置的`float()`函数:
```python
num_str = "3.14"
num_float = float(num_str)
print(num_float) 输出:3.14
3. 使用`eval()`函数:
```python
num_str = "740*+247*(5743+1829)"
num_eval = eval(num_str)
print(num_eval) 输出:
4. 使用`join`结合`int`:
```python
num_list = ['1', '2', '3']
str_list = ''.join(num_list)
print(int(str_list)) 输出:123
```python
str_list = ['1', '2', '3', '4']
int_list = [int(x) for x in str_list]
print(int_list) 输出:[1, 2, 3, 4]
6. 使用`map`函数:
```python
numbers = ['1', '5', '10', '8']
new_numbers = list(map(int, numbers))
print(new_numbers) 输出:[1, 5, 10, 8]
7. 使用`reduce`函数:
```python
from functools import reduce
def str2int(s):
def fn(x, y):
return x * 10 + y
def char2num(s):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
return reduce(fn, map(char2num, s))
print(str2int('23')) 输出:23
8. 使用`eval`函数处理更复杂的表达式:
```python
num_str = "0x12"
num_eval = eval(num_str, {"__builtins__": None}, {"int": int, "float": float})
print(num_eval) 输出:18
请注意,如果字符串无法转换为数字类型,会抛出`ValueError`异常。在使用`eval`函数时要格外小心,因为它会执行字符串中的代码,可能存在安全风险。