Append zeros to the end of a string
Question:
I have two strings I need to make equivalent length:
str1 ='AVFGHJK'
str2 ='ADF'
I need to append some 0
s to the end of str2
so it becomes length equivalent to str1
:
str1 ='AVFGHJK'
str2 ='ADF0000'
Output:
str2 ='ADF0000'
I have tried to use zfill
, but it adds zeros to the beginning of the string, not the end.
Answers:
Use str.ljust
fo padding char
print("ABC".ljust(8, '0')) # ABC00000
And str.rjust
for leading char
print("ABC".rjust(8, '0')) # 00000ABC
String have the zfill
method that appends zeroes to the LEFT; to add them to the right, you could reverse the string:
str2 = str2[::-1].zfill(len(str1))[::-1]
# str2
# Out[14]: 'ADF0000'
But indeed, .rjust
and .ljust
are more versatile!
You can just do it yourself, like that:
str1 ='AVFGHJK'
str2 ='ADF'
str2 = str2 +(len(str1) - len(str2))*'0'
print(str2)
Output:
ADF0000
I have two strings I need to make equivalent length:
str1 ='AVFGHJK'
str2 ='ADF'
I need to append some 0
s to the end of str2
so it becomes length equivalent to str1
:
str1 ='AVFGHJK'
str2 ='ADF0000'
Output:
str2 ='ADF0000'
I have tried to use zfill
, but it adds zeros to the beginning of the string, not the end.
Use str.ljust
fo padding char
print("ABC".ljust(8, '0')) # ABC00000
And str.rjust
for leading char
print("ABC".rjust(8, '0')) # 00000ABC
String have the zfill
method that appends zeroes to the LEFT; to add them to the right, you could reverse the string:
str2 = str2[::-1].zfill(len(str1))[::-1]
# str2
# Out[14]: 'ADF0000'
But indeed, .rjust
and .ljust
are more versatile!
You can just do it yourself, like that:
str1 ='AVFGHJK'
str2 ='ADF'
str2 = str2 +(len(str1) - len(str2))*'0'
print(str2)
Output:
ADF0000