如何在Python中大写字符串的第一个字母,而忽略HTML标记?
我想大写字符串的第一个字母,忽略HTML标记。例如:如何在Python中大写字符串的第一个字母,而忽略HTML标记?,python,django,string,uppercase,Python,Django,String,Uppercase,我想大写字符串的第一个字母,忽略HTML标记。例如: <a href="google.com">hello world</a> 应成为: <a href="google.com">Hello world</a> 我写了下面的代码,虽然有效,但似乎效率低下,因为字符串的每个字符都被复制到输出中。有更好的方法吗 @register.filter def capinit(value): gotOne = False inTag = F
<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
@register.filter
def capinit(值):
gotOne=False
inTag=False
outValue=“”
对于c值:
cc=c
如果c='':
inTag=False
如果不是inTag:
如果c.isalpha()或c.isdigit():
如果没有一个:
cc=c.上()
gotOne=True
outValue=outValue+cc
返回值
请注意,这会忽略初始标点符号。它会将找到的第一个字母大写,除非它先找到一个数字,在这种情况下,它不会将任何内容大写。我试着做你想做的:
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!
html=''
后字母=无
dontcapital=0
afterhtml=“”
对于html中的字符:
如果字符=“/”和后字母=”:
如果dontcapital==0:
afterhtml+=字符.upper()
其他:
afterhtml+=字符
dontcapital=0
其他:
afterhtml+=字符
后字母=字符
打印(HTML后)
#afterhtml是输出!
从我做过的所有测试来看,这应该都有效。如果有人想处理它,你可以。字符串是不可变的,所以任何解决方案都会涉及一些复制。你可能想使用
if…elif
,这样它就不会每次都计算所有条件。不知道为什么不使用,因为它已经存在于python中了,只需要在django中创建一个自定义过滤器,并将输入作为“Hello World”或模板中的任何内容。谢谢,但是由于html标记,诸如大写或capfirst之类的模板过滤器无法工作。谢谢,这与我的解决方案非常相似。为了提高效率,我希望有一些东西不会循环通过每个字符。我不确定是否有可能不循环通过每个字符,因为它需要知道它是否在标记之后。为了提高效率,我不认为这会引起注意,我用我之前制作的一些html进行了测试,大约有600行,只花了1行html。