How does .rjust() work and why it places characters relative to previous one, not to first character – placed most to left – or to left side of screen?
I have an example:
def pairwiseScore(seqA, seqB):
prev = -1
score = 0
length = len(seqA)
similarity = []
relative_similarity = []
for x in xrange(length):
if seqA[x] == seqB[x]:
if (x >= 1) and (seqA[x - 1] == seqB[x - 1]):
score += 3
similarity.append(x)
else:
score += 1
similarity.append(x)
else:
score -= 1
for x in similarity:
relative_similarity.append(x - prev)
prev = x
return ''.join((seqA, '\n', ''.join(['|'.rjust(x) for x in relative_similarity]), '\n', seqB, '\n', 'Score: ', str(score)))
print pairwiseScore("ATTCGT", "ATCTAT"), '\n', '\n', pairwiseScore("GATAAATCTGGTCT", "CATTCATCATGCAA"), '\n', '\n', pairwiseScore('AGCG', 'ATCG'), '\n', '\n', pairwiseScore('ATCG', 'ATCG')
which returns:
ATTCGT
|| |
ATCTAT
Score: 2
GATAAATCTGGTCT
|| ||| |
CATTCATCATGCAA
Score: 4
AGCG
| ||
ATCG
Score: 4
ATCG
||||
ATCG
Score: 10
But I created this with some help from one person. Earlier, this code was devoided of these few lines:
prev = -1
relative_similarity = []
for x in similarity:
relative_similarity.append(x - prev)
prev = x
The method looked like this:
def pairwiseScore(seqA, seqB):
score = 0
length = len(seqA)
similarity = []
for x in xrange(length):
if seqA[x] == seqB[x]:
if (x >= 1) and (seqA[x - 1] == seqB[x - 1]):
score += 3
similarity.append(x)
else:
score += 1
similarity.append(x)
else:
score -= 1
return ''.join((seqA, '\n', ''.join(['|'.rjust(x) for x in similarity]), '\n', seqB, '\n', 'Score: ', str(score)))
and produced this output:
ATTCGT
|| |
ATCTAT
Score: 2
GATAAATCTGGTCT
| | | | | |
CATTCATCATGCAA
Score: 4
AGCG
| | |
ATCG
Score: 4
ATCG
|| | |
ATCG
Score: 10
So I have guessed, that characters processed by .rjust() function, are placed in output, relative to previous ones – NOT to first, most to left placed, character.
Why it works like that? What built-in function can format output, to make every character be placed as i need – relative to the first character, placed most to left side of screen.
str.rjust()doesn’t place anything anywhere; it returns a completely new string containing the old one plus padding on the left side. If you want to put more or less padding due to other text that may appear in the final location then it is your problem to make sure that you use less padding. Perhaps you should consider deferring adding the padding until the output stage, so that it can add the correct amount instead.