Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - make string equal length

Tags:

python

string

I have a RNA sequence of varying length. Max length of the sequence is 22. Some sequences are shorter. So if a sequence is shorter then add "0" to the end of the line till the length becomes 22.

How to do it in python? this is my input

AAGAUGUGGAAAAAUUGGAAUC

CAGUGGUUUUAUGGUAG

CUCUAGAGGGUUUCUG

UUCAUUCGGC

and my expected ouput should be for example in the last line it does not contain 22 characters so i need to make it 22 by adding zero to it

UUCAUUCGGC000000000000

but as per your commands i am getting out put as AAGAUGUGGAAAAAUU 00000 the addtional characters used for justification came down and not in the same line

like image 585
ramko Avatar asked Apr 22 '14 10:04

ramko


People also ask

How do you make two strings equal length in Python?

Use the == and != operators to compare two strings for equality. Use the is operator to check if two strings are the same instance.

How do I fix the length of a string in Python?

In Python, strings have a built-in method named ljust . The method lets you pad a string with characters up to a certain length. The ljust method means "left-justify"; this makes sense because your string will be to the left after adjustment up to the specified length.

Can you use == for strings in Python?

Python comparison operators can be used to compare strings in Python. These operators are: equal to ( == ), not equal to ( != ), greater than ( > ), less than ( < ), less than or equal to ( <= ), and greater than or equal to ( >= ).

How do you trim a string to a specific length in Python?

Use syntax string[x:y] to slice a string starting from index x up to but not including the character at index y. If you want only to cut the string to length in python use only string[: length].


2 Answers

Use str.ljust method:

>>> s = 'foobar'
>>> s.ljust(22, '0')
'foobar0000000000000000'
like image 117
Ashwini Chaudhary Avatar answered Oct 02 '22 09:10

Ashwini Chaudhary


An alternative to @Aशwini चhaudhary's answer is:

s = '{0:0<22}'.format(s)

Example

s = 'hello'
s = '{0:0<22}'.format(s)

>>> print s
hello00000000000000000

Alternative

Or as शwini चhaudhary suggested, simply:

s = format(s, '0<22')
like image 31
sshashank124 Avatar answered Oct 02 '22 07:10

sshashank124