我想输出以下格式:
addr<-9->bit<-15->value<-13->name<-26->type .... ... ...... ...... ...... #..... is the content of each row我使用str.format来实现它:
STRING_FORMATTER = '{0:13}{1:18}{2:18}{3:30}{4:10}\n' content = STRING_FORMATTER.format('addr', 'bit', 'value', 'name', 'type') content = content + STRING_FORMATTER.format('0123', 'LONG STRING THAT EXCEEDS 18 SPACES!!!!!!!!!!!!!!!!', '', '', 'reg') content = content + STRING_FORMATTER.format('00', '0', '0xAD', 'NAME', 'bit') .....我基本上按类型构造字符串。 以上是当第二个字符串超过18个字符空格时,后面的字符串被按下的问题。 有办法解决吗?
或者有没有更好的方法来格式化字符串以前面固定的间距开始?
I want to output the following format:
addr<-9->bit<-15->value<-13->name<-26->type .... ... ...... ...... ...... #..... is the content of each rowI used the str.format to achieve it:
STRING_FORMATTER = '{0:13}{1:18}{2:18}{3:30}{4:10}\n' content = STRING_FORMATTER.format('addr', 'bit', 'value', 'name', 'type') content = content + STRING_FORMATTER.format('0123', 'LONG STRING THAT EXCEEDS 18 SPACES!!!!!!!!!!!!!!!!', '', '', 'reg') content = content + STRING_FORMATTER.format('00', '0', '0xAD', 'NAME', 'bit') .....I basically construct the string by the type. The above is a problem that when the 2nd string exceeds 18 char spaces, the string behind is pushed. Is there a way to solve it?
Or is there a better way to format the string to start at a fixed spacing in front?
最满意答案
要执行您想要的操作,需要在三个字段中拆分字符串。 下面使用的语法要求使用Python 3.5或更高版本的PEP 448 - 使用的附加解包概括功能。 该函数将字符串分成正在跨越的三个字段的正确字段宽度:
STRING_FORMATTER = '{0:13}{1:18}{2:18}{3:30}{4:10}\n' def split(s,*widths): current = 0 for width in widths: yield s[current:current + width] current += width content = STRING_FORMATTER.format('addr', 'bit', 'value', 'name', 'type') content += STRING_FORMATTER.format('0123', *split('LONG STRING THAT EXCEEDS 18 SPACES!!!!!!!!!!!!!!!!',18,18,30), 'reg') content += STRING_FORMATTER.format('00', '0', '0xAD', 'NAME', 'bit') print(content)输出:
addr bit value name type 0123 LONG STRING THAT EXCEEDS 18 SPACES!!!!!!!!!!!!!!!! reg 00 0 0xAD NAME bitTo do what you want requires splitting the string across the three fields. The syntax used below requires Python 3.5 or later for the PEP 448 - Additional Unpacking Generalizations feature used. The function breaks a string into the correct field widths for the three fields being spanned:
STRING_FORMATTER = '{0:13}{1:18}{2:18}{3:30}{4:10}\n' def split(s,*widths): current = 0 for width in widths: yield s[current:current + width] current += width content = STRING_FORMATTER.format('addr', 'bit', 'value', 'name', 'type') content += STRING_FORMATTER.format('0123', *split('LONG STRING THAT EXCEEDS 18 SPACES!!!!!!!!!!!!!!!!',18,18,30), 'reg') content += STRING_FORMATTER.format('00', '0', '0xAD', 'NAME', 'bit') print(content)Output:
addr bit value name type 0123 LONG STRING THAT EXCEEDS 18 SPACES!!!!!!!!!!!!!!!! reg 00 0 0xAD NAME bit更多推荐
发布评论