如何让np.char.add()在拼接的字符串之间添加空格
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

