Python:修改字符串的一部分

时间:2014-04-06 03:16:48

标签: python string

我正在输入一个输入字符串,它是一组连续的字母并将其分成一个句子。问题是,作为初学者,我无法弄清楚如何修改字符串以仅将首字母大写并将其他字母转换为小写字母。我知道string.lower但是将所有内容转换为小写。有什么想法吗?

 # This program asks user for a string run together
 # with each word capitalized and gives back the words
 # separated and only the first word capitalized
 import re
 def main():
      # ask the user for a string
      string = input( 'Enter some words each one capitalized, run together without spaces ')
      for ch in string:
         if ch.isupper() and not ch.islower():
            newstr = re.sub('[A-Z]',addspace,string)
      print(newstr)
 def addspace(m) :
      return ' ' + m.group(0)
 #call the main function
 main()

3 个答案:

答案 0 :(得分:4)

您可以使用capitalize()

  

返回字符串的副本,其第一个字符为大写字母   其余的小写。

>>> s = "hello world"
>>> s.capitalize()
'Hello world'
>>> s = "hello World"
>>> s.capitalize()
'Hello world'
>>> s = "hELLO WORLD"
>>> s.capitalize()
'Hello world'

答案 1 :(得分:0)

无关的例子。要仅将首字母大写:

>>> s = 'hello'
>>> s = s[0].upper()+s[1:]
>>> print s
Hello

>>> s = 'heLLO'
>>> s = s[0].upper()+s[1:]
>>> print s
HeLLO

对于整个字符串,您可以执行

>>> s = 'what is your name'
>>> print ' '.join(i[0].upper()+i[1:] for i in s.split())
What Is Your Name

[编辑]

你也可以这样做:

>>> s = 'Hello What Is Your Name'
>>> s = ''.join(j.lower() if i>0 else j for i,j in enumerate(s))
>>> print s
Hello what is your name

答案 2 :(得分:0)

如果您只想将句子的开头大写(并且您的字符串有多个句子),您可以执行以下操作:

>>> sentences = "this is sentence one. this is sentence two. and SENTENCE three."
>>> split_sentences = sentences.split('.')
>>> '. '.join([s.strip().capitalize() for s in split_sentences])
'This is sentence one. This is sentence two. And sentence three.  '

如果您不想更改不启动句子的字母的大小写,那么您可以定义自己的大写函数:

>>> def my_capitalize(s):
        if s:     # check that s is not ''
            return s[0].upper() + s[1:]
        return s

然后:

>>> '. '.join([my_capitalize(s.strip()) for s in split_sentences])
'This is sentence one. This is sentence two. And SENTENCE three. '