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

给定字符串数组,输出由每个字符串前两个字符组成的数组

问题

给定一个字符串数组,输出一个新数组,其中每个元素为原数组对应字符串的前两个字符。
示例输入:a = ["dog","horse","transform","take"]
示例输出:a = ["do","ho","tr","ta"]

解决方法

Python

用列表推导式简洁处理:

a = ["dog","horse","transform","take"]
new_arr = [s[:2] for s in a]
print(new_arr)  # 输出: ['do', 'ho', 'tr', 'ta']

JavaScript

借助数组的map方法实现:

const a = ["dog","horse","transform","take"];
const newArr = a.map(str => str.slice(0, 2));
console.log(newArr);  // 输出: ["do", "ho", "tr", "ta"]

补充说明

  • 若原数组里有长度小于2的字符串(比如["hi", "a", ""]),截取后会保留现有字符(结果为["hi", "a", ""]),不会抛出异常

内容的提问来源于stack exchange,提问作者Иван Новиков

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:44:51