1

I've been racking my brain for a few days now. I'm fairly new to Python and trying to figure out how to split a string and output the desired contents to a list. I'm trying to select an entire number (regardless of the number of digits in the number) from a string and store it in a variable for future use. My list of strings will look something like this:

["<foo>1</foo>", "<foo>2</foo>", "<foo>3</foo>", "<foo>4</foo>", "<foo>5</foo>", "<foo>6</foo>", "<foo>7</foo>", "<foo>8</foo>", "<foo>9</foo>", "<foo>10</foo>"]

I'm fairly familiar with for loops and the basic concepts of python, but not sure if I've bitten off more than I can chew.

EDIT: I do already have the list in my script. The challenge is to drop the characters surrounding the numbers, leaving only the numbers in the list.

2 Answers 2

1

Python's list() function will turn any string into a list. Also, when you do a for loop on a string, it will iterate every character. So since what you want is a list whose items are <foo> </foo> surrounding every digit in your string:

>>> n = 1234567
>>> L = [ ('<foo>%s</foo>' % i) for i in list(str(n)) ]
>>> print(L)
['<foo>1</foo>', '<foo>2</foo>', '<foo>3</foo>', '<foo>4</foo>', '<foo>5</foo>', '<foo>6</foo>', '<foo>7</foo>']
Sign up to request clarification or add additional context in comments.

Comments

0

I suppose, that you have this as your input (if I understood you correctly):

a = ["<foo>1</foo>", "<foo>2</foo>", "<foo>3</foo>", "<foo>4</foo>", "<foo>5</foo>", "<foo>6</foo>", "<foo>7</foo>", "<foo>8</foo>", "<foo>9</foo>", "<foo>10</foo>"]

The easiest way to find things in a string is a regular expression. Python has the re module for this. As you know list comprehension already, here is a short way of finding all the numbers:

b = [int(re.search(r"\d+", element).group()) for element in a]

\d+ searches for one or more (+) digit (\d).

1 Comment

Much appreciated!

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.