3

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?

2
  • 2
    Are you talking about a string "(\"h1", \"h2\", \"h3\", \"h4\")"? Or a list of strings? Commented Jul 1, 2010 at 18:54
  • 1
    I'm not exactly sure what you are asking here... Are you looking to simply remove the leading 'h' from your strings? Or do you have a long string and need to replace all instances of 'h1' with '1' in it? Commented Jul 1, 2010 at 18:54

2 Answers 2

5
 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 =)

Sign up to request clarification or add additional context in comments.

2 Comments

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. :)
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!
3

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]

1 Comment

ChristopeD: Thanks for this alternate solution. This may come in handy later on in my script. :) Appreciate your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.