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 =" )
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With