如何格式化我的字符串

时间:2014-04-16 22:52:34

标签: python

def main():
    print('Please enter a sentence without spaces and each word has ' + \
          'a capital letter.')
    sentence = input('Enter your sentence: ')

    for ch in sentence:
        if ch.isupper():
            capital = ch
            sentence = sentence.replace(capital, ' ' + capital)


main()

Ex:sentence ='ExampleSentenceGoesHere'

我需要打印为:例句在这里

现在,它打印为:示例句子到达此处(开头有空格)

3 个答案:

答案 0 :(得分:1)

您可以逐字符遍历字符串,并用空格和适当的小写字母替换每个大写字母:

>>> s = 'ExampleSentenceGoesHere'
>>> "".join(' ' + i.lower() if i.isupper() else i for i in s).strip().capitalize()
'Example sentence goes here'

请注意,检查字符串是否为大写由isupper()完成。致电strip()capitalize()只会有助于处理第一封信。

另见相关主题:

答案 1 :(得分:1)

您需要使用capital.lower()将每个大写字母转换为小写字母。你也应该忽略句子的第一个字母,使它保持大写,并且没有空格。你可以使用这样的标志来做到这一点:

is_first_letter = True
for ch in sentence:
    if is_first_letter:
        is_first_letter = False
        continue
    if ch.isupper():
        capital = ch
        sentence = sentence.replace(capital, ' ' + capital.lower())

答案 2 :(得分:0)

我可能会使用rere.split("[A-Z]", text),但我假设你不能这样做,因为这看起来像是家庭作业。怎么样:

def main():
    text = input(">>")
    newtext = ""
    for character in text:
        if character.isupper():
            ch = " " + character.lower()
        else:
            ch = character
        newtext += ch
    text = text[0]+newtext[2:]

你也可以这样做:

transdict = {letter:" "+letter.lower() for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}
transtable = str.maketrans(transdict)
text.translate(transtable).strip().capitalize()

但我认为这超出了作业的范围