DRdr
DRdr

Reputation: 1191

Convert string into integer

How can I convert string into integer and remove every character from that change. Example:

S = "--r10-" I want to have this: S = 10

This not work:

S = "--10-"
int(S)

Upvotes: 4

Views: 4513

Answers (6)

Zile Rehman
Zile Rehman

Reputation: 39

This is simple and does not require you to import any packages.

def _atoi(self, string):
    i = 0
    for c in string:
        i += ord(c)
    return i

Upvotes: 0

Steven Rumbalski
Steven Rumbalski

Reputation: 45542

I prefer Sven Marnach's answer using filter and isdigit, but if you want you can use regular expressions:

>>> import re
>>> pat = re.compile(r'\d+')  #  '\d' means digit, '+' means one or more
>>> int(pat.search('--r10-').group(0))
10

If there are multiple integers in the string, it pulls the first one:

>>> int(pat.search('12 abc 34').group(0))
12

If you need to deal with negative numbers use this regex:

>>> pat = re.compile(r'\-{0,1}\d+')  # '\-{0,1}' means zero or one dashes
>>> int(pat.search('negative: -8').group(0))
-8

Upvotes: 0

Sven Marnach
Sven Marnach

Reputation: 601321

You can use filter(str.isdigit, s) to keep only those characters of s that are digits:

>>> s = "--10-"
>>> int(filter(str.isdigit, s))
10

Note that this might lead to unexpected results for strings that contain multiple numbers

>>> int(filter(str.isdigit, "12 abc 34"))
1234

or negative numbers

>>> int(filter(str.isdigit, "-10"))
10

Edit: To make this work for unicode objects instead of str objects, use

int(filter(unicode.isdigit, u"--10-"))

Upvotes: 10

MatLecu
MatLecu

Reputation: 953

remove all non digits first like that:

int(''.join(c for c in "abc123def456" if c.isdigit()))

Upvotes: 4

use regex replace with /w to replace non word characters with "" empty string. then cast it

Upvotes: 0

Fred Foo
Fred Foo

Reputation: 363467

You could just strip off - and r:

int("--r10-".strip('-r'))

Upvotes: 1

Related Questions