请Python编程高手帮我解答这个问题

这是我的代码 比如现在我有一个字符串“StopAndSmellTheRose" 我想把它变成“Stop and smell the rose"只保留第一个单词的首字母大写。可是run我的程序以后会发现最后得出的结果还是“StopAndSmellTheRose"
我不知道是哪里出错了 请大神帮忙了

def main():
my_str = input("Input a string with each first letter capital.\n")

my_list = list(my_str) #convert a string to a lis
num = 1

if num < len(my_list):
if my_list[num] in ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O' \
'P','Q','R','S','T','U','V','W','X','Y','Z']:
my_list.insert(num, ' ')
else:
num += 1
my_str = ' '.join(my_list)
print(my_str)

main()

程序逻辑存在以下缺陷:
1、没有使用循环对整个列表进行处理,使得只是处理了第二个元素。按照原程序的思路,
if num < len(my_list):
应该改成
while num < len(my_list):

2、如果改为使用while语句,原程序对列表元素的处理算法存在逻辑错误:因为循环到一个大写字母后,会在原位置插入空格,再次循环后,会对空格进行处理;移动到下一个位置后又正好是原来已经处理过得大写字母。如此,会进入死循环。

请参考以下代码:
num = 1
while num < len(my_list):
if my_list[num] in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ': # 这种方式更简洁
my_list[num]=my_list[num].lower() # 转换成小写字母
my_list.insert(num, ' ') # 在该位置插入空格
num += 2 # 跳过插入空格及该字母
else:
num += 1
my_str = ''.join(my_list)
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-10-19
if改成while
====
额,昨天没仔细看,今天回头再看看,现有代码的改动楼上都说了,不过感觉这个问题本身应该用正则表达式去解决是最简单的
>>> s = "StopAndSmellTheRose"
>>> def lower_and_add_space(m):return " " + m.group(0).lower()
>>> s[0] + re.sub("[A-Z]", lower_and_add_space, s[1:])
'Stop and smell the rose'
第2个回答  2013-10-19
import re
t='StopAndSmellTheRose'
t[0]+re.sub(r'([A-Z][a-z]*)',r'\1 ',t).lower()[1:]

第3个回答  2013-10-19
from string import uppercase
def main(s):
length = len(s)
s_copy = s[0]+s[1:length].lower()
new_s = ""
i = 0
for j in range(1,length):
if s[j] in uppercase:
new_s += (s_copy[i:j]+" ")
i = j
new_s += s_copy[i:length]
return new_s
if __name__ == '__main__':
string = raw_input("Input a string with each first letter capital.\n")
new_s = main(string)
print "The real string is:",new_s

相关了解……

你可能感兴趣的内容

大家正在搜

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网