一半君的总结纸

听话只听一半君

#111 如何将数字转换为前面加零/空格的字符串格式,如19→00019?

精神病院有人问的

脑残MEL法

global proc string padString(string $inStr , int $digit){
    string $outStr = "0000000000000000000"+$inStr;
    return `substring $outStr (size($outStr)-$digit+1) (size($outStr)) `;
}

padString("19",5);
// Result: 00019 // 

高科技python法:
Strings:

>>> n = '19'
>>> print n.zfill(5)
>>> '00019'
>>> '19'.rjust(5,'0')
'00019'

And for numbers:

>>> n = 19
>>> print '%05d' % n
>>> 00019
>>> print "{0:05d}".format(19)  # python >= 2.6
>>> 00019
>>> print("{0:05d}".format(19))  # python 3
>>> 00019

增强版:
如何前面后面补空格

>>> s='fuck me'
>>> '%-25s' % s
'fuck me                  '
>>> '%25s' % s
'                  fuck me'

# 如果用format的话
>>> '{message: <16}'.format(message=s)
'fuck me         '
>>> '{message: <25}'.format(message=s)
'fuck me                  '
>>> '{message: <{width}}'.format(message=s, width=25)
'fuck me                  '
>>> '{message:{fill}{align}{width}}'.format(message=s, fill=' ', align='<', width=25)
'fuck me                  '
Advertisements

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s

%d 博主赞过: