Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用f字符串在python中操作字符串:处理长字符串_Python_Python 3.x_String_Formatting - Fatal编程技术网

使用f字符串在python中操作字符串:处理长字符串

使用f字符串在python中操作字符串:处理长字符串,python,python-3.x,string,formatting,Python,Python 3.x,String,Formatting,使用f字符串打印时如何处理长字符串。 我只对字符串的第一个和最后一个n感兴趣(尤其是在本例中,是文件的扩展名)。中间部分应替换为3个点 例如: 而不是: ThisIsMyFilexyz123456s556s54s6afsaf1dshshsb8bbs6s7890.py ThisIsMyFilexyz12345asaggsvrgahhgbargrarbrvs7890.pdf ThisIsMyFilexyz12345asa46189sgvs7890.gif ThisIsMyFilexyz1sgs

使用f字符串打印时如何处理长字符串。 我只对字符串的第一个和最后一个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

导入操作系统,箭头
dirname=input(“输入目录名:”)
def上次修改(文件名):
statinfo=os.stat(文件名)
时间戳=statinfo.st\u mtime
utc=arrow.get(时间戳)
本地=utc.to(‘欧洲/柏林’)
修改的_time=local.format('DD-MMMM-yyy-HH:mm:ss')
返回修改时间
last_time_modified={filename:last_modified(os.path.join(dirname,filename))
用于os.listdir(dirname)中的文件名
如果os.path.isfile(os.path.join(dirname,filename))}
#**打印部分来了**
对于键,上次\u时间中的值\u modified.items():
打印(f'{key:35}')

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

>>> 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

普雷姆·阿南德和维希·曼格拉两人的结合为我做到了这一点。以下是我得到的:

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)
def trunc(arg):
如果len(arg)>35:
返回arg[:25]+“…”+arg[-10:]
其他:
返回参数
对于键,上次\u时间中的值\u modified.items():
行_new='{:35}'。格式(trunc(键),str(值))
打印(新行)

谢谢你们

为什么不直接打印(字符串[:10]+“…”+字符串[-3:])?它不适合我的f-Strings打印风格。除了在左括号和右括号的每一处断开字符串外,别无选择。@blQSheep,不能使用格式设置最大长度。请参见转义序列
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)