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.
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()
...
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With