我正在研究这个脚本,它将获取一个字符串并将其转换为驼峰大小写主题标签。我遇到的问题是,每次我运行代码时,它都会无限期运行,我不完全确定为什么。
if s == "": # a constraint given by the problem
return False
elif len(s) > 140: # a constraint given by the problem
return False
else:
i = 0
while i < len(s)+1:
if s[i] == " ": # if there is a space the next character would be a letter, logically
if s[i+1] != " ": # if the next character is a letter (not a space) it will capitalize it
s[i+1].upper()
i += 1
return "#" + s.replace(" ", "")
即使您像某些答案所暗示的那样正确缩进i += 1
,这也永远不会奏效。你认为这是做什么的:
s[i+1].upper()
Python 中的字符串是不可变的——你不能改变它们。 这会以大写字母的形式返回s[i+1]
,但不会更改s
。 也就是说,这是一个无操作!
让我们看看我们是否可以使您的代码以最少的更改工作:
def hash_camel(s):
if s == "": # a constraint given by the problem
return False
if len(s) > 140: # a constraint given by the problem
return False
string = "#"
i = 0
while i < len(s):
if s[i] == ' ': # if there is a space, the next character could be a letter
if s[i + 1].isalpha(): # if the next character is a letter, capitalize it
string += s[i + 1].upper()
i += 1 # don't process s[i + 1] again in the next iteration
else:
string += s[i]
i += 1
return string
if __name__ == "__main__":
strings = [
'',
'goat',
'june bug',
'larry curly moe',
'never odd or even',
]
for string in strings:
print(hash_camel(string))
输出
> python3 test2.py
False
#goat
#juneBug
#larryCurlyMoe
#neverOddOrEven
>
如果我从头开始写这篇文章,我可能会这样做:
def hash_camel(s):
if s == "" or len(s) > 140: # constraints given by the problem
return None # it's data, not a predicate, return None
words = s.split()
return '#' + words[0] + ''.join(map(str.capitalize, words[1:]))
您会遇到无限循环,因为i += 1
被放置在循环之外。
if s == "": # a constraint given by the problem
return False
elif len(s) > 140: # a constraint given by the problem
return False
else:
i = 0
while i < len(s)+1:
if s[i] == " ": # if there is a space the next character would be a letter, logically
if s[i+1] != " ": # if the next character is a letter (not a space) it will capitalize it
s[i+1].upper()
i += 1
return "#" + s.replace(" ", "")
这是我为你想出的东西:
def cam(s):
if s and len(s) <= 140:
s = s.title().replace(s[0],s[0].lower()).replace(' ','',1)
return "#"+s
return False
print(cam('Camel case words are fun.'))
输出:
#camelCaseWordsAreFun.