Skip to content

Function to pad string with zeros #394

Closed
@ivan-pi

Description

@ivan-pi

Description

A function to pad a string with zeros or another symbol to a given width could be helpful in many cases, especially together with the to_string() function for integer to string conversion.

Currently available methods to achieve this are using concatenation

width = 32
str = "hello"
padded_str = repeat('0',width-len(str)')//str

and perhaps also internal file I/O

write(buffer,'(A32)', blank='zero') "hello"   ! doesn't work for some reason

I propose to add the following functions

! left - padding
function padl(str,width,symbol) result(padded_str)
  character(len=*), intent(in) :: str
  integer, intent(in) :: width
  character(len=1), intent(in), optional :: symbol
  character(len=max(len(str),width) :: padded_str
end function
! right - padding
function padr(str,width,symbol) result(padded_str)
  character(len=*), intent(in) :: str
  integer, intent(in) :: width
  character(len=1), intent(in), optional :: symbol
  character(len=max(len(str),width) :: padded_str
end function

The original string is returned if width < len(str). The default padding symbol could be either the blank symbol ' ' or '0'. Special treatment of a leading sign symbol '+'/'-' might be also desirable.

Prior art

  • Python: zfill
    (Another method to achieve padding in Python is using the string class method .format())
  • Julia: lpad, rpad
  • MATLAB: pad

Metadata

Metadata

Assignees

No one assigned

    Labels

    easyDifficulty level is easy and good for starting into this projectgood first issueGood for newcomersideaProposition of an idea and opening an issue to discuss ittopic: stringsString processing

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions