Pressing_Keys_24_7
Pressing_Keys_24_7

Reputation: 1863

Unable to eliminate a string of characters from a String using "Strip" in Python

I have used the following method to delete a certain trailing string of characters 'lbs' from a string of characters. But, when I run my code and print out the result nothing is changed and the string of characters hasn't been eliminated. Would appreciate your help in this situation! Thanks for the help!

Data:
**Weights:**
0        159lbs
1        183lbs
2        150lbs
3        168lbs
4        154lbs

**Code:**
# Converting the Weights to an Integer Value from a String
for x in Weights:
    if (type(x) == str):
        x.strip('lbs')

**Output:**    
Weights:
0        159lbs
1        183lbs
2        150lbs
3        168lbs
4        154lbs 

Upvotes: 4

Views: 185

Answers (2)

ahmadjanan
ahmadjanan

Reputation: 445

You are stripping the value from the string but not saving it in the list. Try using numeric indexing as follows:

Weights = ['159lbs', '183lbs', '150lbs', '168lbs', '154lbs']

# Converting the Weights to an Integer Value from a String
for x in range(len(Weights)):
    if (type(Weights[x]) == str):
        Weights[x] = Weights[x].strip('lbs')

However, if you aren't comfortable with using a ranged loop, you can enumerate instead as follows:

Weights = ['159lbs', '183lbs', '150lbs', '168lbs', '154lbs']

# Converting the Weights to an Integer Value from a String
for i, x in enumerate(Weights):
    if (type(x) == str):
        Weights[i] = x.strip('lbs')

Upvotes: 1

nectarBee
nectarBee

Reputation: 401

Is this helpful to you..?

Here I haven't used isinstance(line, str) to explicitly check the line whether it is a string or not as the line number is an integer (I suppose). 

with open('Data.txt', 'r') as dataFile:
    dataFile.readline()
    for line in dataFile.readlines():
        number, value = line.strip().split()
        print(value.strip('lbs'))

159
183
150
168
154

Here I have put data into a txt file as;

**Weights:**
0        159lbs
1        183lbs
2        150lbs
3        168lbs
4        154lbs

Upvotes: 1

Related Questions