user2558873
user2558873

Reputation: 15

Python Slicing Newbie

Is there a way in python to store the part I sliced and print only the part I sliced? Meaning on the example below I sliced out "school". I want to just print "school". I will be trying to work on a text file later, where I will just need part of each sentence, but just trying to figure out if its doable with slicing.

word= "the teacher am my school"

a= word[0:-6]

Upvotes: 0

Views: 150

Answers (4)

Luis Y
Luis Y

Reputation: 353

if you want just the last word in a sentence:

word.split()[-1]

Upvotes: 0

dansalmo
dansalmo

Reputation: 11686

Your interpretation of the wording is what is causing confusion. The slice refers to the part that is referenced (or remains), not the part that is removed.

'word'[0] == 'w'   # the slice is 'w' not 'ord'

Upvotes: 0

user2357112
user2357112

Reputation: 281167

print a

I'm not sure what your confusion is.

Update: "school" is the part you didn't slice. If "school" is the part you're interested in, you want

a = word[-6:]

If you want both parts, slice them separately:

notschool, school = word[:-6], word[-6:]

Upvotes: 4

astrognocci
astrognocci

Reputation: 1085

why not slice it directly, then ?

a = word[-6:]

will give you 'school'

Upvotes: 1

Related Questions