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

如何让np.char.add()在拼接的字符串之间添加空格

Fixing Space in Numpy String Concatenation with np.char.add()

Got it, let's sort out that missing space issue when using np.char.add()! Right now, the function just slams the strings together directly without any separator, which is why you're getting merged results like IndianaHoosiers. Here are two simple, clean ways to add that space between your team names and mascots:

Method 1: Add a Space to the First Array First

We can append a space to every element in arr1 (or prepend one to arr2—either works) before doing the final concatenation. Here's how that looks in code:

import numpy as np
arr1 = np.array(['Indiana', 'Cincinnati', 'Purdue', 'Ball State'], dtype=np.str)
arr2 = np.array(['Hoosiers', 'Bearcats','Boilermakers', 'Cardinals'], dtype=np.str)

# Append a space to each element in arr1
arr1_with_space = np.char.add(arr1, ' ')
# Now concatenate with arr2
teams = np.char.add(arr1_with_space, arr2)
print(teams)

Method 2: Nest np.char.add() Calls

If you prefer a concise one-liner, you can nest two np.char.add() calls to insert the space directly between the two arrays:

import numpy as np
arr1 = np.array(['Indiana', 'Cincinnati', 'Purdue', 'Ball State'], dtype=np.str)
arr2 = np.array(['Hoosiers', 'Bearcats','Boilermakers', 'Cardinals'], dtype=np.str)

# Nest add calls to put a space between arr1 and arr2 elements
teams = np.char.add(np.char.add(arr1, ' '), arr2)
print(teams)

Either way, running the code will give you exactly the output you want:

['Indiana Hoosiers' 'Cincinnati Bearcats' 'Purdue Boilermakers' 'Ball State Cardinals']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 12:17:38