簡體   English   中英

遍歷列表時的 Python 字符串格式

[英]Python string formatting when iterating through lists

我有一個簡單的程序,它接受一個句子並計算小寫、大寫、數字和標點字符的數量。 我需要輸出成這樣的格式:

# Upper   # Lower   # Digits  # Punct.
--------  --------  --------  --------
   2         36        4         5    

但是,在我的代碼中,我將標題、條形和計數組合到一個單獨的列表中。 這是我的代碼:

#Prompting user to enter a sentence
input_string = input("Please enter a sentence: ")

#Initializing variables
lowercase_count = 0
uppercase_count = 0
punctuation_count = 0
digits_count = 0

#Iterating through the string to get the counts
for str in input_string:
    if str.isupper():
        uppercase_count +=1
    elif str.islower():
        lowercase_count +=1
    elif str in (".", "?", '!', ",", ";", ":", "-", "\'" ,"\""):
        punctuation_count +=1
    elif str.isnumeric():
        digits_count +=1

header_list = ["# Upper", "# Lower", "# Digits", "# Punct."]
bars_list = ['----------']*4
counts_list = [uppercase_count
               , lowercase_count
               , digits_count
               , punctuation_count]

comb_list = [header_list, bars_list, counts_list]

for list in comb_list:
    print("{:15}{:15}{:15}{:15}".format(list[0], list[1], list[2], list[3]))

這給了我這樣的輸出:

# Upper        # Lower        # Digits       # Punct.       
----------     ----------     ----------     ----------     
              1             16              0              1

如果我要分別打印標題、列表和計數,我可以控制 align 參數

#Printing Header
print("{:15}{:15}{:15}{:15}"
      .format(header_list[0], header_list[1], header_list[2], header_list[3]))

#Printing bars
for header in header_list:
    print("{:15}".format("----------"), end="")

#Printing values
print("\n{:5}{:15}{:15}{:15}"
      .format(uppercase_count
              , lowercase_count
              , digits_count
              , punctuation_count))

這給了我預期的輸出:

# Upper        # Lower        # Digits       # Punct.       
----------     ----------     ----------     ----------     
    1             16              0              1

遍歷列表列表時如何控制 align 參數? 打印輸出的最佳方式是什么?

新回復:

我查看了您的代碼和標題的格式,需要進行一些對齊。 所以試試這個,它會自己居中。 對於每一列,我減去 5 並將其添加到下一列。 原因:每列之間有 5 個字符的空間。 所以我必須為此做出調整。

print("\n{:^10}{:^20}{:^10}{:^20}"

替代方法是:

print("\n{:^10}     {:^10}     {:^10}     {:^10}"

輸出如下:

# Upper        # Lower        # Digits       # Punct.       
----------     ----------     ----------     ----------     
    1              16             0              1          

    32             16             7              12         

  

之前的回復:

您能否嘗試提供以下內容以使其居中:

print("\n{:^15}{:^15}{:^15}{:^15}"

要格式化數據,請使用以下選項之一。 默認情況下,字符串左對齊,數字右對齊。

< is for left justified
> is for right justified
^ is for center justified

您可以在此處了解有關格式化的更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM