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?

2
  • Use the plus + operator? Commented Jun 22, 2022 at 14:03
  • 8
    int(a[1:3]) perhaps? Commented Jun 22, 2022 at 14:04

5 Answers 5

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

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]

2 Comments

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.
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
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]

Comments

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.