python编写程序在一个字符串中找到<>中包住的子字符串
时间: 2023-05-23 08:01:56 浏览: 61
可以使用正则表达式来实现,在 Python 中可以使用 re 模块。下面是一个示例代码:
import re
string = "This is a <sub>sub</sub> string with <bold>bold</bold> and <italic>italic</italic> text."
pattern = "<.*?>" # 匹配以 < 开头,以 > 结尾的最小字符串
matches = re.findall(pattern, string)
print(matches) # 输出 ['<sub>', '</sub>', '<bold>', '</bold>', '<italic>', '</italic>']
这个代码可以找到所有被 <> 包含的字符串,不论它们的内容是什么。
相关问题
python编写一个函数返回字符串中大写字母个数
好的,以下是一个 Python 函数,可以用来计算字符串中大写字母的数量:
```python
def count_uppercase(s):
count = 0
for c in s:
if c.isupper():
count += 1
return count
```
这个函数接受一个字符串参数 `s`,然后遍历字符串中的每个字符。如果字符是大写字母,那么计数器就加一。最后,函数返回计数器的值,即大写字母的数量。你可以像下面这样调用这个函数:
```python
s = "Hello, World!"
count = count_uppercase(s)
print(count) # 输出:2
```
在这个例子中,字符串 `s` 中有两个大写字母,函数返回值为 2。
编写一个Python程序来打印字符串中某个字符的索引。
以下是一个简单的Python程序,它接受一个字符串和一个字符,并打印该字符在字符串中的所有索引:
```python
def print_indexes(string, char):
for i in range(len(string)):
if string[i] == char:
print(i)
string = "Hello World"
char = "l"
print_indexes(string, char)
```
输出:
```
2
3
9
```
该程序定义了一个 `print_indexes` 函数,它使用一个循环来遍历字符串中的每个字符。如果当前字符与指定的字符相同,则打印该字符的索引。在主程序中,我们定义了一个字符串和一个字符,然后调用 `print_indexes` 函数来打印字符在字符串中的所有索引。