Home > Back-end >  How to get integer for two characters in python
How to get integer for two characters in python

Time:06-23

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?

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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]

CodePudding user response:

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]
  • Related