You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中提取字符串各单词的第1、2、3…位字符并按指定格式输出?

解决方案

我们可以用Python实现这个需求,步骤如下:

  1. 拆分字符串为单词列表:使用split()方法将输入字符串按空格分割成独立单词。
  2. 确定提取的轮次:找到最长单词的长度,以此作为需要提取的字符位置总数(比如最长单词有8个字符,就需要提取8组)。
  3. 按位置收集字符并拼接:遍历每个字符位置,依次从每个单词中取出对应位置的字符(如果单词长度足够),拼接成新字符串。

代码示例

input_str = 'I love stack overflow'
words = input_str.split()
max_length = max(len(word) for word in words)

result = []
for i in range(max_length):
    current = ''.join(word[i] for word in words if i < len(word))
    result.append(current)

# 输出结果
for s in result:
    print(f"'{s}'")

运行结果

'Ilso'
'otv'
'vae'
'ecr'
'kf'
'l'
'o'
'w'

代码解释

  • input_str.split():把输入字符串拆分为["I", "love", "stack", "overflow"]。
  • max(len(word) for word in words):计算最长单词的长度(这里是8,对应"overflow")。
  • 循环range(max_length):遍历每个字符位置(0到7,对应第1到第8个字符)。
  • word[i] for word in words if i < len(word):只取单词中存在该位置的字符,避免索引越界。
  • ''.join(...):将收集到的字符拼接成字符串,加入结果列表。

内容的提问来源于stack exchange,提问作者Hunter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 15:12:21