1

If I have a list such as

c=['my', 'age', 'is', '5\n','The', 'temperature', 'today' 'is' ,'87\n']

How do I specifically Convert the numbers of the the list into integers leaving the rest of the string as it is and get rid of the \n ?

expected output:

`c=['my', 'age', 'is', 5,'The', 'temperature', 'today' 'is' ,87]`

I tried using the 'map()' and 'isdigit()' function but it didnt work.

Thank you.

2 Answers 2

1

If you don't know the format of integers in your text, or there are just too many variations, then one approach is simply to try int() on everything and see what succeeds or fails:

original = ['my', 'age', 'is', '5\n', 'The', 'temperature', 'today', 'is', '87\n']
revised = []

for token in original:
    try:
        revised.append(int(token))
    except ValueError:
        revised.append(token)

print(revised)

Generally using try and except as part of your algorithm, not just your error handling, is a bad practice, since they aren't efficient. However, in this case, it's too hard to predict all the possible inputs that int(), or float(), can successfully handle, so the try approach is reasonable.

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

3 Comments

I'm not sure I agree with your last comment, a common idiom in python is EAFP which as per the glossary is characterized by many try, except statements.
@AChampion I understand EAFP but it says, "assumes the existence of valid keys or attributes and catches exceptions", in this case, nearly everything is an exception and we're catching valid keys! I would agree it is Pythonish.
Understood (and agree), though I have found conditional types are another good candidate for EAFP.
1

You can write a function that tries to convert to an int and if it fails return the original, e.g:

def conv(x):
    try:
        x = int(x)
    except ValueError:
        pass
    return x

>>> c = ['my', 'age', 'is', '5\n','The', 'temperature', 'today' 'is' ,'87\n']
>>> list(map(conv, c))
['my', 'age', 'is', 5, 'The', 'temperature', 'todayis', 87]
>>> [conv(x) for x in c]
['my', 'age', 'is', 5, 'The', 'temperature', 'todayis', 87]

Note: 2 strings separated by whitespace are automatically concatenated by python, e.g. 'today' 'is' is equivalent to 'todayis'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.