This is a homework assignment. I just need a nudge.
I'm trying to create a loop in which the letters of a string will be removed when it is beyond a certain number.
Example:
Enter Your String: David
Enter Your Amount: 4
Returns: Davi
What I've made so far:
word = raw_input("Enter your string:")
amount = raw_input("Enter your amount:")
word_length = len(word)
if word_length > amount:
for i in range(word_length):
if s[i] > amount:
And that's just about as far as I've gotten. I'm not very sure as to which syntax I use to delete the letters that are in positions greater than word_length
.
A string itself in Python is immutable -- it cannot be changed and letters cannot be deleted. But you can create new string objects based on your string. One way of doing so is slicing.
Read through the linked section of the official Python tutorial until you find what you need. :)
Edit: If you need to use a loop, as suggested in your comment, another technique is also possible:
Create an empty list.
Loop over the indices range(amount)
and add the letter corresponding to the current index to your list.
Join the list to a string again using "".join(my_list)
.
The purpose of the iterim list is that a list can be altered, while a string -- as said before -- is immutable.