Shashank
Shashank

Reputation: 1135

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!

Upvotes: 1

Views: 973

Answers (4)

user4831228
user4831228

Reputation:

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'

Upvotes: 2

user3641606
user3641606

Reputation:

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'

Upvotes: 0

Duniyadnd
Duniyadnd

Reputation: 4043

The minute you put in a space, original.isalpha() becomes false because a space is not A-Z.

Upvotes: 0

alecxe
alecxe

Reputation: 473873

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'

Upvotes: 2

Related Questions