打印字符串输入并附带一个字符

时间:2019-08-17 15:03:26

标签: python python-3.x

我目前正在学习循环,我做了一个基本的程序,该程序接受字符串输入和整数输入。该程序将打印字符串,并将基于整数输入拆分字符串。我该怎么做?

-------
|jhdsj|
|alhds|
|hja21|
|dasj |
-------

这是我到目前为止所做的

string = input("String = ")
length = int(input("Length = ")

for in range (0, len(string), length):
    print("|", string[i:i+length],"|")

4 个答案:

答案 0 :(得分:1)

执行以下操作:

    $.ajax({ url: "http://localhost:8000/api/v1/todos",
         data: {
          title: title,
          user: "user",
      data: output },
         type: "POST",
                dataType: "json",
                success: function (data, status) {
                    console.log(status);

                },
                contentType : "application/x-www-form-urlencoded",
            });
}

必需的格式可能需要填充额外的空格,这是通过

完成的
string = input("String = ")
length = int(input("Length = "))

string = string + ' ' * (length - (len(string) % length)) #add padding if required
print('-'*(length+2))
for i in range (0, len(string), length):
    print('|' + string[i:i+length] + '|')
print('-'*(length+2))

答案 1 :(得分:1)

如果我猜对了,您需要使用ljust

string = input("String = ")
length = int(input("Length = "))

print('-'*(length+2))
for i in range (0, len(string), length):
    print("|{}|".format(string[i:i+length].ljust(length)))
print('-'*(length+2))

输出:

String = thisisanexample
Length = 4
------
|this|
|isan|
|exam|
|ple |
------

答案 2 :(得分:0)

这应该有效:

string = input("String = ")
length = int(input("Length = "))

if (len(string)%length) > 0:
    string = string + len(string)%length * ' '

for i in range (0, len(string)//length):
    print("|", string[i*length:i*length+length],"|")

答案 3 :(得分:0)

(原则上)您的程序是正确的,我仅修复了语法错误:

string = input("String = ")
length = int(input("Length = "))          # added parenthesis

for i in range(0, len(string), length):   # added variable i
    print("|", string[i:i+length],"|")

输出(带输入):

String = 123456789
Length = 4
| 1234 |
| 5678 |
| 9 |

注意:

如果您希望符号|对齐,则可以使用以下3行代替最后一行(即,代替print("|", string[i:i+length],"|")命令):

    part = string[i:i+length]
    part += (length - len(part)) * " "         # append appropriate number of spaces
    print("|", part,"|")

输出(带输入):

String = 123456789
Length = 4
| 1234 |
| 5678 |
| 9    |