首页 > 解决方案 > 如何在 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

请注意,这会忽略初始标点符号。它将大写它找到的第一个字母,除非它首先找到一个数字,在这种情况下它不会大写任何东西。

标签: pythondjangostringuppercase

解决方案


我试着做你想做的事:

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!

这应该适用于我所做的所有测试。
如果有人想研究它,你可以。


推荐阅读