python格式字符串的长度

时间:2018-06-14 15:21:34

标签: python

我在下面有一些字符串:

123123|00|992|1111
222222|2222|19|922
997997|3333|922|77

我如何格式化(按len排序):

123123|1111|00|992
222222|2222|19|922
997997|3333|77|922

3 个答案:

答案 0 :(得分:1)

使用str.split& str.joinsorted

。{

<强>演示:

s = """123123|00|992|1111
222222|2222|19|922
997997|3333|922|77"""

data = ["|".join(sorted(i.split("|"), key=len, reverse=True)) for i in s.split("\n")]
print( "\n".join(data) )

<强>输出:

123123|1111|992|00
222222|2222|922|19
997997|3333|922|77

答案 1 :(得分:1)

试试这个

pd_occupation <- pd %>% 
  dplyr::filter(LoanStatus == "Chargedoff") %>%
  group_by(Occupation) %>% 
  mutate(group_num = n())

table(pd_occupation$group_num)#to view the distribution

ggplot(subset(pd_occupation, group_num >= 361)) +
  geom_bar(aes(fct_infreq(Occupation)), stat = 'count') +
  ggtitle('Loan Charge-Offs by Occupation')

输出:

a='''123123|00|992|1111
222222|2222|19|922
997997|3333|922|77'''
'\n'.join(['|'.join(sorted(e.split("|"),key=len,reverse=True)) for e in a.split("\n")])

答案 2 :(得分:1)

OP的排序顺序不是基于字符串长度,因为长度为2之前的长度为3(最后两个段)

为此目的,需要自定义排序映射

ranks = {6:0, 4:1, 2:2, 3:3}
text = """123123|00|992|1111
222222|2222|19|922
997997|3333|922|77"""

result = '\n'.join(['|'.join(sorted(line.split('|'),key=lambda x: ranks[len(x)])) 
                    for line in text.split('\n')])
print(result)
# outputs:
123123|1111|00|992
222222|2222|19|922
997997|3333|77|922
相关问题