如何将Python splitlines()生成的列表转为横向形式?附爬虫代码
Hey there! Let's get your split list into a clean horizontal line. The splitlines() method is splitting the tag text into separate list items based on line breaks, so we just need to merge those items back into a single string. Here are a few easy ways to do this:
Method 1: Use str.join() (Simplest Approach)
The join() method lets you concatenate all elements in a list into one string. You can choose a separator (like a space, empty string, or anything else) depending on how you want the final text to look.
Modified Code:
import requests from bs4 import BeautifulSoup url = requests.get('https://sneakernews.com/release-dates/').text soup = BeautifulSoup(url, 'html.parser') tags = soup.find_all('div', {'class': 'col lg-2 sm-3 popular-releases-box'}) for tag in tags: link = tag.find('a').get('href') tag1 = str(tag.text) tag2 = tag1.splitlines() # Convert list to horizontal string horizontal_text = ' '.join([item.strip() for item in tag2 if item.strip()]) print(horizontal_text) # Now prints a single line instead of a list if link == 'javascript:void(0);': link = 'Link not available' print(f"Link: {link}\n") # Optional: Print the link alongside the text
Explanation:
item.strip()removes any extra leading/trailing whitespace (like the trailing space in "March " from your example)if item.strip()filters out empty strings that might come from blank lines in the original text' '.join(...)combines all cleaned elements into one string separated by spaces
Method 2: Use str.replace() (Alternative)
If you don't want to use splitlines() at all, you can directly replace line breaks with spaces in the original text:
# Replace this part of your code: tag1 = str(tag.text) # Instead of splitlines(), replace line breaks horizontal_text = tag1.replace('\n', ' ').strip() print(horizontal_text)
This works because the line breaks in the text are just \n characters—replacing them with spaces gives you a single horizontal line right away.
Either method will turn your list outputs like ['March ', 'OFF WHITE x Nike Air VaporMax'] into clean horizontal text like March OFF WHITE x Nike Air VaporMax.
内容的提问来源于stack exchange,提问作者asd asfdgfbd

