简体   繁体   中英

How to modify and print list items in python?

I am a beginner in python, working on a small logic, i have a text file with html links in it, line by line. I have to read each line of the file, and print the individual links with same prefix and suffix, so that the model looks like this.

<item>LINK1</item>
<item>LINK2</item>
<item>LINK3</item>

and so on.

I have tried this code, but something is wrong in my approach,

def file_read(fname):
        with open(fname) as f:
                #Content_list is the list that contains the read lines.
                content_list = f.readlines()
                for i in content_list:
                    print(str("<item>") + i + str("</item>"))


file_read(r"C:\Users\mandy\Desktop\gd.txt")

In the output, the suffix was not as expected, as i am a beginner, can anyone sort this out for me?

<item>www.google.com
</item>
<item>www.bing.com
</item>

I think when you use.readLine you also put the end of line character into i. If i understand you correctly and you want to print

item www.google.com item

Then try

https://www.journaldev.com/23625/python-trim-string-rstrip-lstrip-strip

print(str("") + i.strip() + str(""))

When you use the readlines() method, it also includes the newline character from your file ("\n") before parsing the next line.

You could use a method called.strip() which strips off spaces or newline characters from the beginning and end of each line which would correctly format your code.

def file_read(fname):
        with open(fname) as f:
                #Content_list is the list that contains the read lines.
                content_list = f.readlines()
                for i in content_list:
                    print(str("<item>") + i.strip() + str("</item>"))


file_read(r"C:\Users\mandy\Desktop\gd.txt")

I assume you wanted to print in the following way www.google.com

When you use readlines it gives extra '\n' at end of each line. to avoid that you can strip the string and in printing you can use fstrings.

with open(fname) as f:
lin=f.readlines()
for i in lin:
    print(f"<item>{i.strip()}<item>")

Another method:

with open('stacksource') as f:
lin=f.read().splitlines()
for i in lin:
    print(f"<item>{i}<item>")

Here splitlines() splits the lines and gives a list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM