检查大写和句号的程序

时间:2014-02-26 09:51:26

标签: python regex string input capitalize

我是初学程序员。我正在尝试写一个会要求判刑的程序,然后检查两件事。 1)句子开头的大写字母和2)句末的句号。我还希望它打印出一个句子,告诉用户他们的句子是否正确。 例如:

输入一句话: python很难。

你的判决不以大写字母开头。

输入一句话: Python很难

你的句子最后没有句号。

输入一句话: python很难

你的判决不以大写字母开头,并且最后没有句号。

最后;

输入一句话:Python很难。

你的判决很完美。

然而,我被困住了,我所拥有的只是这个烂摊子:

sentence = input("Sentence: ")
if sentence[0].isupper():
  print("")
if (sentence[0].isupper()) != sentence:
  print("Your sentence does not start with a capital letter.")
elif "." not in sentence:
  print("Your sentence does not end with a full stop.")
else:
  print("Your sentence is correctly formatted.")

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:2)

试试这个:

sentence = input('Sentence: ') # You should use raw_input if it is python 2.7
if not sentence[0].isupper() and sentence[-1] != '.': # You can check the last character using sentence[-1]
    # both the conditions are not satisfied
    print 'Your sentence does not start with a capital letter and has no full stop at the end.'
elif not sentence[0].isupper():
    # sentence does not start with a capital letter
    print 'Your sentence does not start with a capital letter.'
elif sentence[-1] != '.':
    # sentence does not end with a full stop
    print 'Your sentence does not end with a full stop.'
else:
    # sentence is perfect
    print 'Your sentence is perfect.'

答案 1 :(得分:1)

这有点模块化,因为您可以修改它以获取各种错误消息。

se = "Python is easy"
errors = []
if not se[0].isupper(): errors.append('does not start with a capital letter')
if se[-1] != '.': errors.append('does not end with a full stop')
if errors != []:
   print('Your sentence ' + ' and '.join(errors) + '.')
else:
   print('Your sentence is perfect.')

答案 2 :(得分:0)

se="Python is easy"
if se[0].isupper() and se[-1]=='.':
   print 'ok'
else:
   print 'Not ok'

更新:

您可以使用strip函数删除字符串开头和结尾处不必要的空格。

se="Python is hard."
se=se.strip()
if se[0].isupper():
    if se[-1]=='.':
        print 'Your sentence is correctly formatted.'
    else:
        print 'Your sentence has no full stop at the end.'
elif se[0].islower() and se[-1]!='.':
    print 'Your sentence doesnt start with a capital letter and has no full stop at the end.'
else:
    print 'Your sentence does not start with a capital letter.'