python - 如何在 Python 中将字符串的第一个字母大写,而忽略 HTML 标记?
问题描述
我想将字符串的第一个字母大写,忽略 HTML 标签。例如:
<a href="google.com">hello world</a>
应该变成:
<a href="google.com">Hello world</a>
我写了以下内容,它有效,但似乎效率低下,因为字符串的每个字符都被复制到输出中。有更好的方法吗?
@register.filter
def capinit(value):
gotOne = False
inTag = False
outValue = ''
for c in value:
cc = c
if c == '<':
inTag = True
if c == '>':
inTag = False
if not inTag:
if c.isalpha() or c.isdigit():
if not gotOne:
cc = c.upper()
gotOne = True
outValue = outValue + cc
return outValue
请注意,这会忽略初始标点符号。它将大写它找到的第一个字母,除非它首先找到一个数字,在这种情况下它不会大写任何东西。
解决方案
我试着做你想做的事:
html = '<a href="google.com">hello world</a>'
afterletter = None
dontcapital = 0
afterhtml = ""
for character in html:
if character == "/" and afterletter == "<":
afterhtml += character
dontcapital = 1
elif afterletter == ">":
if dontcapital == 0:
afterhtml += character.upper()
else:
afterhtml += character
dontcapital = 0
else:
afterhtml += character
afterletter = character
print(afterhtml)
#afterhtml is the output!
这应该适用于我所做的所有测试。
如果有人想研究它,你可以。
推荐阅读
- javascript - 如何在javascript中让char不被somechar包围
- python-iris - 根据坐标而不是索引更改虹膜立方体中的值
- apache-spark - 如何确保输出数据帧是动态分区的,使得每个分区大约为 128mb?
- flutter - 扑。根据子画布绘图设置父级的高度
- spring-boot - 如何根据文件类型选择要运行的春季批处理作业
- typescript - Nexus Prisma - 如何在全球范围内使用 crud 处理 createdAt 和 updatedAt?
- python - 为什么在运行 jupyter notebook 时出现错误?
- angular - 如果值是异步的,如何在函数中使用 ngModel 旧值?
- google-cloud-functions - Firebase Cloud Functions-ImageMagick CLI PDF to images
- c# - 修复用户输入在输入的用户输入循环以匹配其在数组中的索引之前不会继续