views:

61

answers:

2

hi all...

how would I go about taking a string ("h1", "h2", "h3, "h4")

And substituting these values with numbers 1, 2, 3, 4?

Correspondingly, how I would I preform the same operation but on a list instead?

Thanks in advance...

+3  A: 
 to_replace = ["h1","h2","h3","h4"]
 replaced = [ int(s.replace("h","")) for s in to_replace ]

If this is what you want.

It's not exactly clear; I'm assuming that your input is not literally a string "(\"h1\", \"h2\", \"h3\", \"h4\")", but a list of strings.

And I'm not sure what you meant by your second question, as it appears to be the same as the first.

I will update my answer accordingly =)

Justin L.
To MikeD: Yeah, basically that is what I want to do. To give some context, I am trying translate R code into Python and what I am trying to do is build a multi-dimensional array out of 3 strings/lists/whatever that contain 4 elements per string/list. I guess first off, what is better to use for building an array: a list or a string? You'll have to please forgive my cryptic descriptions because I am a n00b with Python. :)
myClone
To Justin: I apologize for my unclear question. Its partially because I am not sure what it is that I am after. I have an R script that I am trying to translate. (I know there is rPy to handle this stuff automagically, but I am trying to learn Python by translation). What you offered looks close. In R it reads like this: hClasses <- as.numeric(gsub("h", "", segmentsH)). I tried what you had but wrote it this way: segmentsH = ["h1", "h2", "h3", "h4"] <br> hClasses = [ int(s.replace("h","")) for s in segmentsH ].Worked perfectly. Many thanks!
myClone
+1  A: 

This would strip out every non-numeric character (not only h):

>>> s = ["h1", "h2" , "h3" , "h4"]
>>> [int(filter(lambda c: c.isdigit(), x)) for x in s]
[1, 2, 3, 4]

or

>>> s = ["x1", "b2" , "c3" , "h4"]
>>> [int(filter(lambda c: c.isdigit(), x)) for x in s]
[1, 2, 3, 4]
ChristopheD
ChristopeD: Thanks for this alternate solution. This may come in handy later on in my script. :) Appreciate your help.
myClone