Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extra newline in output when adding strings

Tags:

python

I have a text file something like,

3 forwhomthebelltolls
-6 verycomplexnumber

The question is, if the integer K is positive, take the first K characters and put them at the end of the string. If it's negative, take the last K characters and put them at the front of the string. Like this:

whomthebelltollsfor
numberverycomplex

My code is

file = open("tex.txt","r")

for line in file:
    K, sentence = int(line.split(" ")[0]), line.split(" ")[1]
    new_sentence = sentence[K:] + sentence[:K]
    print(new_sentence)

however it prints the values like:

whomthebelltolls
for
numberverycomplex

I do not understand why this happens. I am just adding two strings however in printing part the second part that I add goes down.

like image 204
camarman Avatar asked May 12 '26 07:05

camarman


2 Answers

The actual contents of the file:

3 forwhomthebelltolls\n
-6 verycomplexnumber

When you iterate through the file with for line in file, you're taking the entire line, including the newline character at the end. You're never removing that. And so, sentence[K:] resolves to whomthebelltolls\n, and sentence[:k] resolves to for. The entire string is whomthebelltolls\nfor. Since there's a newline in the middle of the string, that gets printed.

To fix this, strip the string first:

for line in file:
    K, sentence = int(line.split(" ")[0]), line.split(" ")[1].strip()
    ...
like image 89
Green Cloak Guy Avatar answered May 13 '26 21:05

Green Cloak Guy


if you iterate over a file line-by-line, each line will contain the trailing newline, so in the first iteration line is really forwhomthebelltolls\n

now when you construct the new_sentence you do:

 new_sentence = 'forwhomthebelltolls\n'[3:] + 'forwhomthebelltolls\n'[:3]
              =    'whomthebelltolls\n'     + 'for'
              = 'whomthebelltolls\nfor'

which prints as:

whomthebelltolls
for

to get rid of the trailing newline, use .strip() (as in line=line.strip())

like image 29
umläute Avatar answered May 13 '26 20:05

umläute