Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String or list substitution in Python

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?

like image 585
myClone Avatar asked Jun 30 '26 10:06

myClone


2 Answers

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

like image 53
Justin L. Avatar answered Jul 01 '26 23:07

Justin L.


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]
like image 43
ChristopheD Avatar answered Jul 01 '26 22:07

ChristopheD