Печать Python до / после разных строк - PullRequest
0 голосов
/ 04 марта 2019

Я давно создал некоторый код, который помогает создать таблицу в BBcode, используемую на форумах.

counter = 0
counter2 = 0
while True:
        UserInput = input("")
    if counter2 == 0:
        print ("[tr]")
    print ("[td][center]Label\n" + "[img]" + str(UserInput) + "[/img][/center][/td]")
    counter += 1
    counter2 += 1
    if counter % 5 == 0:
        print ("[/tr]")

Так что, если я введу Image1.jpg ~ Image7.jpg в отдельных строках, вывод будетпоказано ниже

> [tr] 
> [td][center]Label[img]Image1.jpg[/img][/center][/td] 
> [td][center]Label[img]Image2.jpg[/img][/center][/td] 
> [td][center]Label[img]Image3.jpg[/img][/center][/td] 
> [td][center]Label[img]Image4.jpg[/img][/center][/td] 
> [td][center]Label[img]Image5.jpg[/img][/center][/td] 
> [/tr]
> [td][center]Label[img]Image6.jpg[/img][/center][/td] 
> [td][center]Label[img]Image7.jpg[/img][/center][/td] 

В настоящее время код вставляет только [/ tr] в конце каждого из 5 изображений. Как сделать так, чтобы [/ tr] также печатался в конце вывода независимо от того,сколько jpgs введено?

Как я могу напечатать [tr] в начале и соединить его со строкой ниже, а затем не печатать снова, пока не будет напечатан [/ tr]?

Извиняюсь за мой дерьмовый английский и навыки объяснения.

(Текущий прогресс)

counter = 0
while True:
    UserInput = input("")
    if counter == 0 or counter % 5 == 0:
        print("[tr]", end = "")
    print ("[td][center]Label\n" + "[img]" + str(UserInput) + "[/img][/center][/td]")
    counter += 1
    if counter % 5 == 0:
        print("[/tr]")

Ответы [ 3 ]

0 голосов
/ 06 марта 2019

Разделите функции.Получите список изображений, затем обработайте его:

def bbcode(images):
    for i in range(0,len(images),5):
        print('[tr]')
        for image in images[i:i+5]:
            print(f'[td][center]Label[img]{image}[/img][/center][/td]')
        print('[/tr]')

def get_images():
    images = []
    while True:
        image = input('Image? ')
        if not image: break
        images.append(image)
    return images

images = get_images()
bbcode(images)

Вы можете сделать это одним длинным скриптом, но это не так ясно:

count = 0

while True:
    image = input('Image? ')
    if not image:
        break

    count = (count + 1) % 5
    if count == 1:
        print('[tr]')
    print(f'[td][center]Label[img]{image}[/img][/center][/td]')
    if count == 0:
        print('[/tr]')

if count != 0:
    print('[/tr]')
0 голосов
/ 06 марта 2019

Ниже приведен результат с некоторыми комментариями.Чтобы обновить ваши спецификации, просто установите для переменной max_item_blocks значение, которое вы хотите.

### your main body element with {} to pass a number
element = '[td][center]Label[img]Image{}.jpg[/img][/center][/td]'

### The number of "blocks" you want to print.
max_item_blocks = 3

### Define a start value of 1
start = 1

### Our simple loop with join() function
while max_item_blocks > 0:

    ### End value is start + 5
    end = start + 5

    print('[tr]\n' + '\n'.join([element.format(i) for i in range(start, end)]) + '\n[\\tr]')

    ### Start takes ending value
    start = end

    ### Ending value is now start + 5
    end = start + 5

    ### Reduce our block counts by 1
    max_item_blocks -= 1

Выход для 3 блоков:

[tr]
[td][center]Label[img]Image1.jpg[/img][/center][/td]
[td][center]Label[img]Image2.jpg[/img][/center][/td]
[td][center]Label[img]Image3.jpg[/img][/center][/td]
[td][center]Label[img]Image4.jpg[/img][/center][/td]
[td][center]Label[img]Image5.jpg[/img][/center][/td]
[\tr]
[tr]
[td][center]Label[img]Image6.jpg[/img][/center][/td]
[td][center]Label[img]Image7.jpg[/img][/center][/td]
[td][center]Label[img]Image8.jpg[/img][/center][/td]
[td][center]Label[img]Image9.jpg[/img][/center][/td]
[td][center]Label[img]Image10.jpg[/img][/center][/td]
[\tr]
[tr]
[td][center]Label[img]Image11.jpg[/img][/center][/td]
[td][center]Label[img]Image12.jpg[/img][/center][/td]
[td][center]Label[img]Image13.jpg[/img][/center][/td]
[td][center]Label[img]Image14.jpg[/img][/center][/td]
[td][center]Label[img]Image15.jpg[/img][/center][/td]
[\tr]
0 голосов
/ 04 марта 2019

После прочтения того, что вы написали 5 раз, я верю, что вы хотите:

    print("[tr]")
    while True:
        counter = 0
        UserInput = input("")
        if UserInput == "exit":
            exit(0)
        print("[tr]", end = "")
        while (counter !=5):
            print ("[td][center]Label\n" + "[img]" + str(UserInput) + "[/img][/center][/td]")
            counter += 1
        print ("[/tr]")
    print("[/tr]")

Итак, что происходит, вы печатаете [tr] в той же строке, что и первый отпечаток изнутри, пока выв розыске.[/ tr] находится в новой строке, но вы можете поместить ее в ту же строку, добавив end = "" ко второму выводу.

...