Home > database >  Extract number from the string
Extract number from the string

Time:10-10

I'm solving an assignment in python and found it difficult to extract a number from a string. It is to read data from a file and extract numbers from strings and perform operations on the value.

Tesla Model 3 LR 4WD:560
Tesla Model Y LR 2WD:540

This is a string and I have to extract only the value after the colon.

CodePudding user response:

Split the string at \n characters. Then for every line, split it at : and append the number to a list:

string = "Tesla Model 3 LR 4WD:560\nTesla Model Y LR 2WD:540"

lines = string.split("\n")
nums = []

for line in lines:
    nums.append(int(line.split(":")[-1]))

CodePudding user response:

Split the string at \n characters. Then for every line, split it at : and append the number to a list:

string = "Tesla Model 3 LR 4WD:560\nTesla Model Y LR 2WD:540"
lines = string.split("\n")
nums = []
for line in lines:
    nums.append(int(line.split(":")[-1]))

CodePudding user response:

I assume that you get data as string. Also, you need value after the colon.

Then you can use split function from string.

data = "Tesla Model 3 LR 4WD:560"
value = data.split(":")[-1]

CodePudding user response:

If you can use a regex:

string = 'Tesla Model 3 LR 4WD:560\nTesla Model Y LR 2WD:540'

import re

out = re.findall('(?<=:)\d ', string)

Output: ['560', '540']

If you want integers:

out = [int(x.group()) for x in re.finditer('(?<=:)\d ', string)]

Output: [560, 540]

CodePudding user response:

This snippet should read strings from file, and extract the numbers from the strings into a list.

def findNumber(text):
    # Returns the number after the colon as integer.
    return int(text.split(':')[-1])

# Open the file containing the lines/strings
with open('file.txt') as file:
    lines = file.readlines()

# extract the number fr
data = list(map(findNumber, lines))

print(data)
  • Related