用python编写用户输入一个姓名,将中间位用星号替换掉
时间: 2024-02-27 20:51:18 浏览: 98
可以使用Python的字符串操作来实现中间位用星号替换的功能。具体代码如下:
```python
name = input("请输入姓名:")
length = len(name)
if length <= 2:
print("输入的姓名太短了")
else:
middle = name[1:length-1]
star = "*" * len(middle)
new_name = name[0] + star + name[length-1]
print("替换后的姓名为:", new_name)
```
在这段代码中,首先需要获取用户输入的姓名。接着,通过`len()`函数获得姓名的长度,判断是否可以进行替换。如果长度小于等于2,那么直接输出提示信息。否则,使用切片操作获取中间的部分,使用`*`运算符生成相同长度的星号字符串,将星号替换到中间的部分,最后再将新的字符串输出即可。
相关问题
用户输用Python编写程序入一个姓名,将中间位用星号替换掉,
可以使用字符串的切片和替换来实现这个功能,具体代码如下:
```python
name = input("请输入姓名:")
length = len(name)
if length % 2 == 0:
# 姓名长度为偶数时,替换中间的两个字符
replace_str = '**'
index = length // 2 - 1
new_name = name[:index] + replace_str + name[index+2:]
else:
# 姓名长度为奇数时,替换中间的一个字符
replace_str = '*'
index = length // 2
new_name = name[:index] + replace_str + name[index+1:]
print("替换后的姓名为:", new_name)
```
这段代码会先判断输入的姓名的长度是奇数还是偶数,然后计算出需要替换的中间字符的位置。最后使用字符串的切片和替换操作生成替换后的姓名,并输出。
编写函数测试用户输入中是否有敏感词,如果有的话就把敏感词替换为3个星号***,然后将替换后的用户的输入作为函数的返回值进行输出
以下是一个简单的Python函数,用于测试用户输入中是否有敏感词,并将敏感词替换为3个星号:
```python
def sensitive_words_filter(user_input, sensitive_words):
for word in sensitive_words:
user_input = user_input.replace(word, '***')
return user_input
```
其中,`user_input`是用户的输入字符串,`sensitive_words`是一个包含敏感词的列表。
你可以这样使用它:
```python
sensitive_words = ['敏感词1', '敏感词2', '敏感词3']
user_input = input('请输入文本:')
filtered_input = sensitive_words_filter(user_input, sensitive_words)
print(filtered_input)
```
这个函数将会把用户输入中的所有敏感词都替换为3个星号,然后将替换后的文本作为函数的返回值输出。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)