【问题标题】:Manipulating strings in python with f strings: handling long strings使用 f 字符串在 python 中操作字符串:处理长字符串
【发布时间】:2020-07-28 11:44:52
【问题描述】:

使用 f-Strings 打印时如何处理长字符串。 我只对字符串的第一个和最后一个 n 感兴趣(尤其是在这种情况下是文件的扩展名)。中间部分应替换为 3 个点。

举个例子:

代替:

ThisIsMyFilexyz123456s556s54s6afsaf1dshshsb8bbs6s7890.py

ThisIsMyFilexyz12345asaggsvrgahhgbargrarbrvs7890.pdf

ThisIsMyFilexyz12345asa46189sgvs7890.gif

ThisIsMyFilexyz1sgsgbs6rahhgbargrarbrvs7890.jpg

我想要这个:

ThisIsMyFilexy...123.py

ThisIsMyFilexy...456.pdf

ThisIsMyFilexy...789.xml

ThisIsMyFilexy...001.gif

ThisIsMyFilexy...002.py
 
ThisIsMyFilexy...003.py

    import os, arrow
    
    dirname = input("Enter a directory name: ")
    
    def last_modified(filename):
        statinfo = os.stat(filename)
        timestamp = statinfo.st_mtime
        utc = arrow.get(timestamp)
        local = utc.to('Europe/Berlin')
        modified_time = local.format('DD MMMM YYYY HH:mm:ss')
        return modified_time
    
    
    last_time_modified = { filename : last_modified(os.path.join(dirname, filename))
                    for filename in os.listdir(dirname)
                    if os.path.isfile(os.path.join(dirname, filename))}
    
# **here comes the printing part**
    for key, value in last_time_modified.items():
        print(f'{key:<35} {value:>35}')

【问题讨论】:

  • 为什么不只是 print(string[:10]+"..." +string[-3:])?
  • 它不适合我的 f-Strings 打印风格。
  • 只能在左右括号的每一段处断字符串。
  • @blQSheep,您无法使用格式设置最大长度
  • python.org/dev/peps/pep-0498/#id27。见Escape sequences

标签: python python-3.x string formatting


【解决方案1】:

@Prem Anand 和@Vishesh Mangla 两者结合为我做到了。这是我得到的:

def trunc(arg):
    if len(arg) > 35:
      return arg[:25]+"..."+arg[-10:]
    else:
        return arg

for key, value in last_time_modified.items():
    line_new = '{:<38}  {:>35}'.format(trunc(key), str(value))
    print(line_new)

谢谢你们!

【讨论】:

    【解决方案2】:

    定义一个可以截断长字符串并以您喜欢的任何格式返回的新函数,并在 f-string 中使用该函数

    >>> def trunc(s, left=14, right=6, seperator='...'):
    ...     return s[:left]+seperator+s[-right:]
    ... 
    >>> 
    >>> for key in lines:
    ...     print(f'{trunc(key)}')
    ... 
    ThisIsMyFilexy...890.py
    ThisIsMyFilexy...90.pdf
    ThisIsMyFilexy...90.gif
    ThisIsMyFilexy...90.jpg
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-27
      • 1970-01-01
      • 2010-10-30
      • 2021-11-15
      • 2013-07-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多