擅长:python、mysql、java
<p>假设在<code>file.txt</code>中有文本,则可以执行以下操作:</p>
<pre class="lang-py prettyprint-override"><code>with open("file.txt") as f:
content = f.readlines()
content = [value.strip()[::-1] if idx % 2 != 0 else value.strip() for idx, value in enumerate(content)]
print(content)
>> ['Easter eggs,', 'Yellow and blue,', 'Easter eggs,', 'For me and you.', '', '', 'Easter eggs,', 'Candy sweet,', 'Easter eggs,', 'Are good to eat.']
</code></pre>
<p><strong>解释:</strong>我正在读取文件<a href="https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list">as suggested in this community question</a>,然后枚举内容以检查文件索引是否可被2整除(<code>idx % 2 != 0</code>)</p>
<p><strong>编辑:</strong>如果需要换行符并希望将邮件粘贴到单个字符串中,可以执行以下操作:</p>
<pre class="lang-py prettyprint-override"><code>print('\n'.join(content))
</code></pre>
<p>输出:</p>
<pre><code>Easter eggs,
Yellow and blue,
Easter eggs,
For me and you.
Easter eggs,
Candy sweet,
Easter eggs,
Are good to eat.
</code></pre>