How to remove leading and trailing spaces from a string?
Question:
I’m having a hard time trying to use .strip
with the following line of code:
f.write(re.split("Tech ID:|Name:|Account #:",line)[-1])
Answers:
Expand your one liner into multiple lines. Then it becomes easy:
f.write(re.split("Tech ID:|Name:|Account #:",line)[-1])
parts = re.split("Tech ID:|Name:|Account #:",line)
wanted_part = parts[-1]
wanted_part_stripped = wanted_part.strip()
f.write(wanted_part_stripped)
You can use the strip()
method to remove trailing and leading spaces:
>>> s = ' abd cde '
>>> s.strip()
'abd cde'
Note: the internal spaces are preserved.
Should be noted that strip()
method would trim any leading and trailing whitespace characters from the string (if there is no passed-in argument). If you want to trim space character(s), while keeping the others (like newline), this answer might be helpful:
sample = ' some stringn'
sample_modified = sample.strip(' ')
print(sample_modified) # will print 'some stringn'
strip([chars])
: You can pass in optional characters to strip([chars])
method. Python will look for occurrences of these characters and trim the given string accordingly.
Starting file:
line 1
line 2
line 3
line 4
Code:
with open("filename.txt", "r") as f:
lines = f.readlines()
for line in lines:
stripped = line.strip()
print(stripped)
Output:
line 1
line 2
line 3
line 4
I’m having a hard time trying to use .strip
with the following line of code:
f.write(re.split("Tech ID:|Name:|Account #:",line)[-1])
Expand your one liner into multiple lines. Then it becomes easy:
f.write(re.split("Tech ID:|Name:|Account #:",line)[-1])
parts = re.split("Tech ID:|Name:|Account #:",line)
wanted_part = parts[-1]
wanted_part_stripped = wanted_part.strip()
f.write(wanted_part_stripped)
You can use the strip()
method to remove trailing and leading spaces:
>>> s = ' abd cde '
>>> s.strip()
'abd cde'
Note: the internal spaces are preserved.
Should be noted that strip()
method would trim any leading and trailing whitespace characters from the string (if there is no passed-in argument). If you want to trim space character(s), while keeping the others (like newline), this answer might be helpful:
sample = ' some stringn'
sample_modified = sample.strip(' ')
print(sample_modified) # will print 'some stringn'
strip([chars])
: You can pass in optional characters to strip([chars])
method. Python will look for occurrences of these characters and trim the given string accordingly.
Starting file:
line 1
line 2
line 3
line 4
Code:
with open("filename.txt", "r") as f:
lines = f.readlines()
for line in lines:
stripped = line.strip()
print(stripped)
Output:
line 1
line 2
line 3
line 4