Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending a string to each item of an array

I have an array and when I try to append a string to it the array converts to a single string.

I have the following data in an array:

$Str  
451 CAR,-3 ,7 ,10 ,0 ,3 , 20 ,Over: 41  
452 DEN «,40.5,0,7,0,14, 21 ,  Cover: 4  

And I want to append the week of the game in this instance like this:

$Str = "Week"+$Week+$Str 

I get a single string:

Week16101,NYG,42.5 ,3 ,10 ,3 ,3 , 19 ,Over 43 102,PHI,-  1,14,7,0,3, 24 ,  Cover 4 103,

Of course I'd like the append to occur on each row.

like image 796
Riskworks Avatar asked Jan 01 '17 00:01

Riskworks


People also ask

How do you add a string to all elements in an array?

The easiest way to append all elements in an array into one is the join() method of the Array class. It joins all the elements into a string with the given optional delimiter.

How do you add items to each element in an array?

If you are using array module, you can use the concatenation using the + operator, append(), insert(), and extend() functions to add elements to the array. If you are using NumPy arrays, use the append() and insert() function.

Can you append items to an array?

When you want to add an element to the end of your array, use push(). If you need to add an element to the beginning of your array, try unshift(). And you can add arrays together using concat().

How do I append a string to an array in PowerShell?

The + operator in PowerShell is used to add items to various lists or to concatenate strings together. To add an item to an array, we can have PowerShell list all items in the array by just typing out its variable, then including + <AnotherItemName> behind it.


1 Answers

Instead of a for loop you could also use the Foreach-Object cmdlet (if you prefer using the pipeline):

$str = "apple","lemon","toast" 
$str = $str | ForEach-Object {"Week$_"}

Output:

Weekapple
Weeklemon
Weektoast
like image 77
Martin Brandl Avatar answered Oct 17 '22 07:10

Martin Brandl