简体   繁体   中英

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 

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')

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM