0

Hi there!

Let me start by saying this-- I have no experience with regular expressions. Simply put, I want a function that turns an array [eg: func(array)] into... an array, but add ONE space on both values. Meaning:

array = ['red','blue'] #returns ['red','blue']
array = func(array) # returns [' red ',' blue ']

Is it possible to do this? If so, how would I? If you could show me an example, and explain how you did it, that would be great! Thanks!

3
Contributors
8
Replies
9
Views
8 Years
Discussion Span
Last Post by Dekudude
0

You don't need regex for this:

>>> array = ['red','blue']
>>> array1 = [' %s ' % item for item in array]
>>> array1
[' red ', ' blue ']
>>>
0

When you want to transform the elements of a list one by one, use the map function like this

def unstrip(theStr):
  return " %s " % theStr

theArray = ["red", "blue"]
# prints [" red ", " blue "]
print map(unstrip, theArray)

The list comprehension is posible too :)

0

I don't want to change the variable, per se, I just want to be able to check it as if the variable WAS like that through an if statement... does that make sense? I don't want to change the variable, I just want the value in my if statement to have the spaces.

0

It would be easier if we could see the if statement you need. Is it something like this ?

if map(unstrip, theArray) == [" red ", " blue "]:
  ...
0
def func(array)
      #stuff
arr = ['valueA','valueB']
if ' valueA ' in func(arr):
      #true

does this make sense?

0

It makes sense, but you should perhaps transform the value instead of the whole array, like this

if otherfunc(valueA) in arr:
  ...

for example here

arr = ["valueA", "valueB"]
if " valueA ".strip() in arr:
  ...
0

Thanks for your quick response-- unfortunately, in my case, that will not work, as I need the array's VALUES to have the whitespace... it's hard to explain, but that's what I need. :P Thanks!

0

Hmm... it's not letting me edit my post-- I got this working, though. Thanks, guys!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.