ThanaDaray
ThanaDaray

Reputation: 1693

How to print words in a range in Python?

Suppose I have the below string:

"Python is a programming language that lets you work more quickly and integrate your systems more effectively. You can learn to use Python and see almost immediate gains in productivity and lower maintenance costs."

Start word position: 5
End word position: 10

Any suggestions for printing all the words from position from 5 to 10?

Upvotes: 0

Views: 3278

Answers (3)

Óscar López
Óscar López

Reputation: 236004

Like this, assuming words is the string:

print words.split()[4:10]

Upvotes: 3

ATOzTOA
ATOzTOA

Reputation: 35950

Assuming you need entire words (not characters) from position 5 to 10 both inclusive, you can do the following:

print sentence.split(" ")[4:10]

For example:

>>> print "Python is a programming language that lets you work more quickly \
       and integrate your systems more effectively. You can learn to use \
       Python and see almost immediate gains in productivity and lower \
       maintenance costs.".split(" ")[4:10]

['language', 'that', 'lets', 'you', 'work', 'more']

Upvotes: 3

IT Ninja
IT Ninja

Reputation: 6430

This is basic stuff, you would do:

print "my words are right here haha lol"[5:11]

You should most likely take a look at: http://effbot.org/zone/python-list.htm as python strings are similar to list's, and many list functions can be performed on them, such as indexing, which is what your question asks about.

Upvotes: -4

Related Questions