Leow
Leow

Reputation: 13

Get word's line by using splitlines and Split

I want to get the word in which line according to the text that user have enter.

Here is sample of code:

numLine =0

text = "How do you do? Am i \nsuppose to go somewhere?\nHere is the line i 
        don't know"

splittext= text.splitlines()
for i in splittext:
    numLine += 1
    if 'suppose' in i.split():
        print(str(numLine)+": "+i )

after text is insert and get the word line,

for i in splittext:
       numLine += 1

After that i try to split again if it is match with 'suppose' word from splittext

        if 'suppose' in i.split():
        print(str(numLine)+": "+i )

the outcome of the print suppose to give

2: suppose to go somewhere?

But the terminal doesn't show the print. How do i fix this problem?

Upvotes: 0

Views: 401

Answers (2)

Dan R
Dan R

Reputation: 1494

Here is a more Pythonic way to solve your problem.

text = "How do you do? Am i \nsuppose to go somewhere?\nHere is the line i don't know"

for index, line in enumerate(text.splitlines()):
    if 'suppose' in line.split():
        print('{}: {}'.format(index + 1, line))

Explanation:

  • Avoid creating extra variables such as splittext if you are only using them one time
  • Use enumerate() when you want to iterate over a list and also do something with the counters
  • Use string formatting rather than concatenation to print stuff nicely.

Upvotes: 3

pecey
pecey

Reputation: 681

Did you mean text2.splitlines() instead of text.splitlines()?

Upvotes: 1

Related Questions