簡體   English   中英

用Python處理字符串,多行字符串和列表的優雅方式

[英]Elegant way to handle strings, multi-line-strings and lists in Python

我在Python中有一個自定義的日志函數,我想以Python的方式將輸入分成多行。 輸入可以是字符串,多行字符串或列表。

這適用於字符串和多行字符串,但是不能處理列表:

def log( text, indent = 0):
    indent_level = 4
    current_time = str( datetime.datetime.now().time())[0:-3]
    for line in text.splitlines():
        log_line = current_time + ' | ' + indent_level * indent * ' ' + str( line)
        print( log_line)

您如何建議也可以處理列表而又不復雜

if( type( string) == list):

到處測試?

在方法開始時,請使用鴨子類型對輸入進行一次標准化。

try:
    # Assume you get multiline text
    lines = text.splitlines()
except AttributeError:
    # If your assumption was wrong, then you should already have a list
    lines = text

暫無
暫無

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

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