0

I would like to add one space before and after each string in Python. I have 851 files. The first file contains 219 lines. The last file contains 1069 lines. Some line are just dots while other lines are numbers. I would like to use the center() function. I tried:

import os, os.path

for x in range(1, 852):
    input_file_name = f"9.{x}.txt"
    output_file_name = os.path.join(f"10.{x}.txt")
    with open(input_file_name) as input_file:
        with open(output_file_name, "w") as output_file:
            for input_line in input_file:
                output_line = input_line.center(2)
                output_file.write(output_line)

This does not add any space. I want one space before each string and one space after each string.

Input

.
.
.
.
.
.
.
25
.
.
.
.
55

Expected output

x.x
x.x
x.x
x.x
x.x
x.x
x.x
x25x
x.x
x.x
x.x
x.x
x55x

NB : x stands for space. Any help would be appreciated. Thanks.

1
  • The length of each line matters! So take that into consideration. Commented Apr 7, 2020 at 6:36

2 Answers 2

2

Each input_line in the above code will contain a newline at the end \n thus in your case you need to remove the \n character thus we can use rstrip() to remove newline and format line as you needed.

Code

 for input_line in f:
        output_line = " " + input_line.rstrip("\n") + " \n"
        output_file.write(output_line)

Output

 . 
 . 
 . 
 . 
 . 
 25 
 . 
 . 
 . 
 . 
 . 
 . 

Sign up to request clarification or add additional context in comments.

5 Comments

This does not add any space after the numbers.
okay .. is it compulsory to use center method . the reason was that the number has 2 digits hence taking center would leave the last 2 position with numbers
Yes, I want to use the center method.
without using center it would be easy . output_line = " " + input_line.rstrip("\n") + " \n"
output_line = " " + input_line.rstrip("\n") + " \n" is working. Thank you.
0

Moin Yellowcab,

as I understand correctly you can use the .join string method to add any values to the beginning and the end of a string.

#insert character into string with string-method .join

string_1 = 'this is a string without a space at the beginning or end. Put a X where the spacing should be'


iterable_join = ['X', 'X',] 
string_1 = string_1.join(iterable_join)
print(string_1)

Output in my console is:

Xthis is a string without a space at the begining or end. put an x where the spacing should beX

I don't know if this creates too much overhead but it does work. For more information see:

https://www.tutorialspoint.com/python/string_join.htm

If it helped you to solve the question please mark as answer. Best, CJ

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.