0

I'm supposed to write code in Python to remove the first and last letters in each word of a string, depending on a certain variable. So far I've tried several methods and I get some errors each time:

def trimWords(s, fromStart=1, fromEnd = 1):
    return [word - word[:fromStart] - word[-fromEnd:] for word in s if word > fromStart + fromEnd]

This is what I've come up with but unfortunately it leaves me with a TypeError which I cannot find.

feedMe
  • 3,431
  • 2
  • 36
  • 61
ebeilin
  • 11
  • 1
  • 4
  • Welcome to StackOverflow. You should read the [FAQ](http://stackoverflow.com/tour), [How to Ask](http://stackoverflow.com/help/how-to-ask), and [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) to ask better questions. In this case, use proper indentation in your second line, and give the full example input and traceback for the error message you get. – Rory Daulton Feb 26 '17 at 00:16

3 Answers3

1

access the string as an array and use slicing

def trim_word(word, from_start=0, from_end=0):
    return word[from_start:len(word) - from_end]

print(trim_word('hello')) # 'hello'
print(trim_word('hello',1,1)) # 'ell'

note: no boundary conditions are considered

Community
  • 1
  • 1
Crispin
  • 2,070
  • 1
  • 13
  • 16
1

So I think you want to remove the first and last letters in each word of a string, say, like a sentence. How about this for a starting point:

import string
s = "The quick brown fox, and so on."
s = [a[1:-1] for a in s.translate(None, string.punctuation).split()]
print s

Output:

['h', 'uic', 'row', 'o', 'n', '', '']

The s.translate(None, string.punctuation) removes all punctuation from the string, as explained here. The .split() then splits the string, by default at the spaces. Finally, we are iterating over all of the strings in the split string which correspond to the individual words, and slicing off the first and last characters.

Use this as a starting point and adapt it if you have more complicated strings that require further consideration.

Community
  • 1
  • 1
feedMe
  • 3,431
  • 2
  • 36
  • 61
0

This example might help you

s = ":dfa:sif:e" print s[1:]