简体   繁体   中英

Python: Not able to slice string

I am trying to make one program using python where User has to put value which is equal to any name or any word and what it does is that it cut first letter of the word and paste it at the end of the word and adds 2 more alphabet equal to 'py'.


Ex- Enter the value: Shashank 'Output which i am getting is shashankspy' but the value which I want is 'hashankspy'

The code which i made is this:

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' 

I am not able to get the real value. Please help!

You need to stake a slice from the word [1:] :

new_word = word[1:] + first + pyg

Also, instead of checking the length for being more than zero, just check for emptiness:

if original and original.isalpha():

Demo:

>>> 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'

There is one simple error which you are making and it can be done as:

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'

由于空格不是AZ,因此在您放入空格的那一刻,original.isalpha()变为false。

You can also do like adding

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM