Python 字符串处理:分行输出并去除空格

本程序接收一个整数 N 和多行字符串,先输出前 N 行字符串,然后将剩余字符串按空格或回车分隔,并去除空格后输出。

示例输入

'3' 'Hello world!' 'I am a robot.' 'Let's talk about AI.'

'I' 'love' 'coding.'

'Python' 'is' 'awesome!'

示例输出

'Hello world!' 'I am a robot.' 'Let's talk about AI.'

'I love coding.'

'Python' 'is' 'awesome!'

代码实现

N = int(input())

lines = []
while True:
    line = input()
    if line == '':
        break
    lines.append(line)

for i in range(N):
    print(lines[i])

print()

for i in range(N, len(lines)):
    words = lines[i].split()
    for word in words:
        print(word)
    if i < len(lines) - 1:
        print()

代码解析

  1. 使用 input() 函数读取输入的整数 N 和多行字符串,并将字符串存储在列表 lines 中。
  2. 使用 for 循环遍历前 N 行字符串,并使用 print() 函数输出。
  3. 使用 print() 函数输出一个空行,用于分隔前 N 行和剩余字符串。
  4. 使用 for 循环遍历剩余字符串,使用 split() 函数将每个字符串按空格分割成单词列表。
  5. 使用嵌套 for 循环遍历每个单词列表,并使用 print() 函数输出每个单词。
  6. 使用 if 语句判断是否为最后一行,如果非最后一行,则输出一个空行,用于分隔不同行输出。

注意:

本程序假设输入的字符串之间使用空行分隔,并且剩余字符串中不包含空格。如果输入格式不同,则需要修改代码以适应新的格式。

Python 字符串处理:分行输出并去除空格

原文地址: https://www.cveoy.top/t/topic/oIMH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录