我正在尝试使用python创建一个程序,其中User必须放置等于任何名称或任何单词的值,它的作用是它剪切单词的第一个字母并将其粘贴到单词的末尾并且增加2个字母等于'py'。
前 - 输入值:Shashank '我得到的输出是shashankspy',但我想要的价值是'hashankspy'
我所做的代码就是:
pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
print original
word = original.lower()
first = word[0]
new_word = word + first + pyg
new_word[1:]
else:
print 'empty'
我无法获得真正的价值。请帮忙!
答案 0 :(得分:2)
您需要从单词[1:]
中获取切片:
new_word = word[1:] + first + pyg
此外,不要检查长度是否大于零,只需检查空虚:
if original and original.isalpha():
演示:
>>> def make_new_word(s):
... pyg = 'py'
... if s and s.isalpha():
... word = s.lower()
... first = word[0]
... new_word = word[1:] + first + pyg
... return new_word
... else:
... return 'empty'
...
>>> original = raw_input('Enter a word: ')
Enter a word: Shashank
>>> make_new_word(original)
'hashankspy'
答案 1 :(得分:2)
您正在制作一个简单的错误,可以这样做:
new_word = new_word[1:len(new_word)]
pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
print original
word = original.lower()
first = word[0]
new_word = word + first + pyg
new_word = new_word[1:len(new_word)]
else:
print 'empty'
答案 2 :(得分:0)
你放入空格的那一刻,original.isalpha()变为假,因为空格不是A-Z。
答案 3 :(得分:0)
您也可以添加
new_word = new_word [1:len(new_word)]
pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
print original
word = original.lower()
first = word[0]
new_word = word + first + pyg
new_word = new_word[1:len(new_word)]
else:
print 'empty'