append differing number of characters to strings in list of strings

  • Last Update :
  • Techknowledgy :

Another solution is to use str.ljust

[i.ljust(4) for i in strs]

You can use python's format. The general form for format specifier is:

format_spec:: = [
   [fill] align
][sign][#][0][width][, ][.precision][type]

so, if you provide the width it will be padded with space:

>>> list(map('{:4}'.format, strs))['aa  ', 'bbb ', 'c   ', 'dddd']
>>> [i + " " * (4 - len(i)) for i in strs]
['aa  ', 'bbb ', 'c   ', 'dddd']

Suggestion : 2

Last Updated : 16 Jun, 2022

The original list: [1, 3, 4, 5]
The original string: gfg
The list after appending is: [1, 3, 4, 5, 'gfg']

Suggestion : 3

Remote Work 2022 , Remote Work 2022

Syntax of join():
string.join(iterable)
Code to convert python list to string using join():
flexiple = ["Hire", "the", "top", "freelancers"]

print(" ".join(flexiple))

#Output - "Hire the top freelancers"

As aforementioned let us try to use join() on an iterable containing an int. It would return a typeerror.

flexiple = ["Hire", "the", "top", 10, "python", "freelancers"]

print(" ".join(flexiple))

#Output - TypeError: sequence item 3: expected str instance, int found
Code to convert python list to string using map():
flexiple = ["Hire", "the", "top", 10, "python", "freelancers"]

print(" ".join(map(str, flexiple)))

#Output - "Hire the top 10 python freelancers"

This method is slow and must only be used to help understand the concept of converting lists to strings in python.

flexiple = ["Hire", "the", "top", 10, "python", "freelancers"]

f1 = ""

for i in flexiple:
   f1 += str(i) + " "

print(f1)

#Output = "Hire the top 10 python freelancers "