<p>我正在Hackerrank上做<a href="https://www.hackerrank.com/challenges/capitalize" rel="nofollow noreferrer">this</a>问题,我提出了这个想法,包括分割输入并在之后加入它(参见下面的实现)。但是,其中一个测试用例包含输入(<strong>hello</strong><;multiple spaces>;<strong>world</strong>),这会使我的代码崩溃,因为输入字符串在每个单词之间有超过1个空格。所以,我只是想知道是否有人能帮我修复我的代码,我只是想知道如何在Python中计算一个字符串中有多少个空格(尤其是多个空格)。我在Java中发现了如何计算空格,但在Python中没有。为了测试,我附上了照片。</p>
<p>提前谢谢。</p>
<p><strong><em>我的实现:</em></strong></p>
<pre><code>input_string = input()
splitter = input_string.split()
final = []
for i in range(0,len(splitter)):
for j in range(0,len(splitter[i])):
if(j==0):
final.<a href="https://www.cnpython.com/list/append" class="inner-link">append</a>(splitter[i][j].upper())
else:
final.append(splitter[i][j])
# Assumed that there is one space btw each words
final.append(' ')
print(''.join(final))
</code></pre>
<blockquote>
<p>For Test case pic,</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/mx6AZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mx6AZ.png" alt="enter image description here"/></a></p>
<pre><code>import re
line = "Hello World LoL"
total = 0
for spl in re.findall('\s+', line):
print len(spl)
total += len(spl) # 4, 2
print total # 6
>>> 4
>>> 2
>>> 6
</code></pre>