Home > Software design >  Python: Can not multiply sequence by non-int of type 'str':: Separating characters from nu
Python: Can not multiply sequence by non-int of type 'str':: Separating characters from nu

Time:12-14

I have an input string, each element has a number and character which I want to access each element number and character separately as the following:

1s-2r,3d*3 # this is the line in the input file: # this stars means repeated three time 

So I want to make an array includes only numbers as:

number_only=[1,2,3,3,3] # numpy 
s=[s,r,d,d,d] # another array string characters only 

But I got the following erros "TypeError: can't multiply sequence by non-int of type 'str'".. I know that this should be a intger but I do not know how to do that, attached is the trial code

import numpy as np
with open('dataa.dat', 'r') as f:
     input_data = f.readlines()
     input_data = [(d ' ')[:d.find('#')].rstrip() for d in input_data]
x   =          input_data[0].split('-')
y =          []

for elt in x:
    if "*" in elt:
        n, mult        = elt.split("*")
        y        = y   [(n)] * (mult)
    else:
        y =[ii for ii in elt.split(',')]
number_only        =          np.array(y)
#s

CodePudding user response:

This returns numbers from a string:

only_digits = ''.join(i for i in string if i.isdigit())

CodePudding user response:

You might try this:

import re

def split_string(pat):
    numbers = []
    letters = []

    for s in re.split(r"[,-]", pat):
        count = 1
        if len(s) > 2:
            assert s[2] == '*'
            count = int(s[3:])
        numbers  = [int(s[0])] * (count)
        letters  = [s[1]] * (count)

    return numbers, letters

def main():
    # The two examples from the question and the comments
    numbers, letters = split_string("1s-2r,3d*3")
    assert numbers == [1,2,3,3,3]
    assert letters == ['s','r','d','d','d']

    numbers, letters = split_string("1s,2e*3-2q*2,1u")
    assert numbers == [1,2,2,2,2,2,1]
    assert letters == ['s', 'e', 'e', 'e', 'q', 'q', 'u']


if __name__ == '__main__':
    main()

CodePudding user response:

Simple way to do this is with regex:

import re

string = "1s-2r,3d*3"
numbers = re.findall(r"[0-9]", string)
letters = re.findall(r"[a-zA-Z]", string)

Then to convert numbers from str to int:

numbers = [int(i) for i in numbers]

Edit:

This should do it

def parse_string_to_numbers_letters(string):
    string_parts = re.split(r",|-", str(test))
    aggregated_string = ""
    for string in string_parts:
        if re.search("\*", string):
            to_be_multipled = string.split("*")[0]
            multiplier = string.split("*")[1]
            string = to_be_multipled * int(multiplier)
        aggregated_string  =string
    numbers = re.findall(r"[0-9]", aggregated_string)
    letters = re.findall(r"[a-zA-Z]", aggregated_string)
    return numbers, letters
  • Related