user6223604
user6223604

Reputation:

How to delete letters [A-Z] with python

I want to delete letters from a string and save which is deleted in variable from these lines as below :

Input =

1.785K

10MEG

999.1V

Expected :

Value = 1.785
Units detected = K

Value = 10
Units detected = MEG

Value = 999.1
Units detected = V

I try this code but doens't work

list = ['1.785K','10MEG','999.1V']
for l in list:
  l.replace("[A-Z]", "")
  print("Value =" + l) 
  print("Units detected =" )

Upvotes: 3

Views: 1748

Answers (3)

Daweo
Daweo

Reputation: 36390

You might use str translate method to get rid of unwanted characters

import string
t = str.maketrans('','',string.ascii_uppercase)
data = ["1.785K","10MEG","999.1V"]
for d in data:
    print(d.translate(t))

Output:

1.785
10
999.1

maketrans accepts 3 arguments, 2 first are empty in this case, because we need only to remove characters, not replace. However as you need these unit I suggest using re for that following way:

import re
data = ["1.785K","10MEG","999.1V"]
for d in data:
    print(re.findall(r'(.*?)([A-Z]+)',d))

Output:

[('1.785', 'K')]
[('10', 'MEG')]
[('999.1', 'V')]

Upvotes: 2

Strange
Strange

Reputation: 1540

There you go:

I've solved this using regex

import re


input = '''1.785K

10MEG

999.1V
'''

for val,unit in re.findall('([0-9\.]+)([A-Za-z]+)',input):
    print('Value : ',val)
    print('Units : ',unit)
    print()

Output:

Value :  1.785
Units :  K

Value :  10
Units :  MEG

Value :  999.1
Units :  V

Regex link:

https://regex101.com/r/DZIaUM/1

Upvotes: 2

Adam.Er8
Adam.Er8

Reputation: 13393

Because seems like your units are always at the end, you can avoid using regex and just use str.rstrip instead.

It removes a suffix of characters that can be provided as a string containing all chars to remove. the module string defines ascii_uppercase that contains all A-Z chars.

as for getting the deleted chars, you can use the length of the stripped string to slice the original string and get exactly the removed chars

try this:

from string import ascii_uppercase

list = ['1.785K','10MEG','999.1V']
for l in list:
  after_strip = l.rstrip(ascii_uppercase)
  stripped_chars = l[len(after_strip):]
  print("Value = " + l) 
  print("Units detected = " + stripped_chars)

Upvotes: 4

Related Questions