python字符串练习题
时间: 2025-05-12 22:33:47 浏览: 50
### Python 字符串练习题及相关代码
以下是几个常见的 Python 字符串操作练习题及其对应的代码示例:
#### 题目 1:判断一个字符串是否是另一个字符串的子串
可以通过 `str.count()` 方法来统计某个子串在目标字符串中的出现次数。如果返回值大于零,则说明该子串存在。
```python
s = input("请输入字符串1:")
s1 = input("请输入字符串2:")
if s.find(s1) != -1:
print(f"{s1} 是 {s} 的子串") # 使用 find() 函数替代 count()
elif s1.find(s) != -1:
print(f"{s} 是 {s1} 的子串")
else:
print("两个字符串互相不包含")
```
---
#### 题目 2:判断输入的字符串是否为回文字符串
可以先将字符串转为小写并去除非字母数字字符,然后再通过切片反转的方式验证其正序和逆序是否相同。
```python
import re
def is_palindrome(s):
cleaned_s = ''.join(re.findall(r'[a-zA-Z0-9]', s)).lower() # 去除非字母数字字符并转换为小写
return cleaned_s == cleaned_s[::-1]
input_str = input("请输入一串字符串:")
result = is_palindrome(input_str)
if result:
print("这是一个回文字符串")
else:
print("这不是一个回文字符串")
```
---
#### 题目 3:将二进制字符串转换为十进制整数
利用内置函数 `int` 并指定基数为 2 来完成此任务。
```python
binary_str = input("请输入一个二进制字符串:")
decimal_value = int(binary_str, base=2)
print(f"二进制字符串 {binary_str} 转换为十进制后的值为:{decimal_value}")
```
---
#### 题目 4:统计字符串中每个单词的频率
给定一段文字,将其分割成多个单词,并计算每个单词出现的频次。
```python
from collections import Counter
text = input("请输入一段文本:").strip().split()
word_count = Counter(text)
for word, freq in word_count.items():
print(f"'{word}' 出现了 {freq} 次")
```
---
#### 题目 5:替换字符串中的特定模式
假设需要将字符串中的所有数字替换成星号 (`*`)。
```python
import re
original_string = input("请输入原始字符串:")
modified_string = re.sub(r'\d', '*', original_string) # 将匹配到的数字替换为 '*'
print(f"修改后的字符串为:{modified_string}")
```
---
阅读全文
相关推荐


















