1
a = "a26lsdm3684"

How can I get an integer with value of 26(a[1] and a[2])? If I write int(a[1) or int (a[2]) it just gives me integer of one character. What should I write when I want integer with value of 26 and store it in variable b?

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
Marcin Sochacki
  • 35
  • 1
  • 1
  • 3

5 Answers5

3

Slice out the two characters, then convert:

b = int(a[1:3])  # Slices are exclusive on the end index, so you need to go to 3 to get 1 and 2
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
0

you can get substrings out of the string and convert that to int, as long as you know the exact indexes

a = "a26lsdm3684"

substring_of_a = a[1:3]
number = int(substring_of_a)

print(number, type(number))
Utshaan
  • 92
  • 8
0

There is more than one way to do it.
Use Slicing, as pointed out by jasonharper and ShadowRanger.
Or use re.findall to find the first stretch of digits.
Or use re.split to split on non-digits and find the 2nd element (the first one is an empty string at the beginning).

import re

a = "a26lsdm3684"

print(int(a[1:3]))
print(int((re.findall(r'\d+', a))[0]))
print(int((re.split(r'\D+', a))[1]))
# 26
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
0

A little more sustainable if you want multiple numbers from the same string:

def get_numbers(input_string):
    i = 0
    buffer = ""
    out_list = []
    while i < len(input_string):
        if input_string[i].isdigit():
            buffer = buffer + input_string[i]
        else:
            if buffer:
                out_list.append(int(buffer))
            buffer = ""
        i = i + 1
    if buffer:
        out_list.append(int(buffer))

    return out_list

a = "a26lsdm3684"
print(get_numbers(a))

output:

[26, 3684]
testfile
  • 2,145
  • 1
  • 12
  • 31
  • If you want multiple numbers at arbitrary offsets, you'd just use `re.findall(r'\d+', input_string)` to pull them all at once without a complicated parsing loop. – ShadowRanger Jun 22 '22 at 14:12
  • Agreed. You can use regex. I however don't like to reach for it in stack overflow for these simple questions since regex will most likely go over OP's head. A for loop can be better understood. albeit complicated – testfile Jun 22 '22 at 14:16
0

If you want to convert all the numeric parts in your string, and say put them in a list, you may do something like:

from re import finditer
a = "a26lsdm3684"
s=[int(m.group(0)) for m in finditer(r'\d+', a)] ##[26, 3684]
gimix
  • 3,431
  • 2
  • 5
  • 21