Python 用字符串选择函数
时间: 2024-04-20 18:21:28 浏览: 13
在Python中,可以使用字符串来选择函数的一种常见方式是使用字典。你可以创建一个字典,将字符串作为键,将对应的函数作为值。然后,根据给定的字符串,在字典中查找对应的函数并调用它。
以下是一个示例代码:
```python
def func1():
print("这是函数1")
def func2():
print("这是函数2")
def func3():
print("这是函数3")
# 创建一个字典,将字符串与对应的函数关联起来
function_dict = {
"func1": func1,
"func2": func2,
"func3": func3
}
# 根据用户输入的字符串选择对应的函数并调用
user_input = input("请输入函数名:")
if user_input in function_dict:
selected_func = function_dict[user_input]
selected_func()
else:
print("无效的函数名")
```
在上面的示例中,我们定义了三个函数func1、func2和func3,并创建了一个字典function_dict来关联字符串与对应的函数。然后,根据用户输入的字符串选择对应的函数并调用。
相关问题
python 的字符串处理函数
Python 中常用的字符串处理函数有很多,以下是一些常见的:
1. len():返回字符串的长度。
2. str.upper():将字符串中的所有字母转换为大写。
3. str.lower():将字符串中的所有字母转换为小写。
4. str.capitalize():将字符串的第一个字母转换为大写。
5. str.title():将字符串中每个单词的首字母转换为大写。
6. str.strip():去掉字符串开头和结尾的空格。
7. str.replace(old, new):将字符串中的 old 子串替换为 new 子串。
8. str.split():将字符串按照空格或指定字符分割成列表。
还有很多其他的字符串处理函数,可以根据具体需求选择使用。
python中字符串替换函数
Python中字符串替换函数有很多,这里介绍其中的几个:
1. `replace()`函数
`replace()`函数可以将字符串中的某个子串替换成指定的字符串。该函数的语法如下:
```python
str.replace(old, new[, count])
```
其中:
- `old`:要被替换的子串。
- `new`:用于替换 `old` 的新字符串。
- `count`:可选参数,指定替换的次数。
示例:
```python
my_str = "Hello, World!"
new_str = my_str.replace("World", "Python")
print(new_str) # 输出:Hello, Python!
```
2. `translate()`函数
`translate()`函数可以将字符串中的某些字符替换成指定的字符。该函数的语法如下:
```python
str.translate(table)
```
其中:
- `table`:翻译表,可以使用 `maketrans()` 函数生成。
示例:
```python
my_str = "Hello, World!"
table = str.maketrans("o", "0")
new_str = my_str.translate(table)
print(new_str) # 输出:Hell0, W0rld!
```
3. `sub()`函数
`sub()`函数是 `re` 模块中的函数,用于正则表达式替换。该函数的语法如下:
```python
re.sub(pattern, repl, string, count=0, flags=0)
```
其中:
- `pattern`:正则表达式。
- `repl`:用于替换的字符串。
- `string`:要被替换的字符串。
- `count`:可选参数,指定替换的次数。
- `flags`:可选参数,指定正则表达式的匹配模式。
示例:
```python
import re
my_str = "Hello, 123!"
new_str = re.sub(r"\d+", "World", my_str)
print(new_str) # 输出:Hello, World!
```
以上是常用的几个字符串替换函数,根据需求选择合适的函数即可。