4

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 
6
  • 1
    x.strip('lbs') generated a new string, with the indicated letters removed from the ends. However, this accomplished absolutely nothing, as you didn't do anything with the new string. Commented Jan 22, 2021 at 17:29
  • @jasonharper Thanks for the help! I assigned x = x.strip('lbs') but, nothing changed in the Weights! Commented Jan 22, 2021 at 17:33
  • @Pressing_Keys_24_7 check my answer. It changes the values in weights. You can't change a list value just by iterating over it. You need to specify the index. Commented Jan 22, 2021 at 17:38
  • @ahmadjanan I see. Thanks for the help:) Commented Jan 22, 2021 at 18:02
  • @ahmadjanan I am trying to figure some other way as well! Given an upvote:) Commented Jan 22, 2021 at 18:02

2 Answers 2

1

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')
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.