修改字符串后保留第一个位置大小写

时间:2017-10-07 00:20:45

标签: python string

我正在编写一个程序,将输入词改为猪拉丁语。我的代码工作,除了大写之外,一切都是应该的。如果输入的单词以大写字母开头,我想做第一个位置,即单词[0]大写。我尝试了很多方法,但似乎无法弄明白。任何帮助将不胜感激。

word=input("Enter the word: ")

word=word.lower()

if word.isalpha():
  if word[0:len(word)] not in ' ':
    if word[0] in 'aeiou':
      word=word + 'yay'
      print(word)
    elif word[0:1] in 'qu':
      word=word[2:]+word[0]+word[1] +'ay'
      print(word)
    elif word[0] not in 'aeiou':
      while(word[0] not in 'aeiou'):
        word=word[1:]+word[0:1]
      word=word+'ay'
      print(word)

  else:
    print("Invalid Word")
else:
  print("Invalid Word")

2 个答案:

答案 0 :(得分:0)

试试这个:

#!/usr/bin/python

capitalize = False

word=input("Enter the word: ")

if word[0] in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
    capitalize = True

word = word.lower()

if word.isalpha():
  if word[0:len(word)] not in ' ':
    if word[0] in 'aeiou':
      word=word + 'yay'
    elif word[0:1] in 'qu':
      word=word[2:]+word[0]+word[1] +'ay'
    elif word[0] not in 'aeiou':
      while(word[0] not in 'aeiou'):
        word=word[1:]+word[0:1]
      word=word+'ay'
  else:
    print("Invalid Word")
else:
  print("Invalid Word")

if capitalize is True:
    word = word.title()

print(word)

答案 1 :(得分:0)

您可以尝试这种方式:

word=input("Enter the word: ")

if word[0].isupper() and word.isalpha():
    word=word.lower()
    if word[0:len(word)] not in ' ':
      if word[0] in 'aeiou':
        word=word + 'yay'
        print(word[0].upper() + word[1:])
      elif word[0:1] in 'qu':
        word=word[2:]+word[0]+word[1] +'ay'
        print(word[0].upper() + word[1:])
      elif word[0] not in 'aeiou':
        while(word[0] not in 'aeiou'):
          word=word[1:]+word[0:1]
        word=word+'ay'
        print(word[0].upper() + word[1:])
    else:
      print("Invalid Word")

elif word[0].islower() and word.isalpha():
    word=word.lower()
    if word[0:len(word)] not in ' ':
      if word[0] in 'aeiou':
        word=word + 'yay'
        print(word)
      elif word[0:1] in 'qu':
        word=word[2:]+word[0]+word[1] +'ay'
        print(word)
      elif word[0] not in 'aeiou':
        while(word[0] not in 'aeiou'):
          word=word[1:]+word[0:1]
        word=word+'ay'
        print(word)
    else:
      print("Invalid Word")

else:
  print("Invalid Word")

为了更好地理解这里的编译above代码。