Last caracter of a string truncated issue when working from the end of the string - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Last caracter of a string truncated issue when working from the end of the string (/thread-35142.html) |
Last caracter of a string truncated issue when working from the end of the string - Teknohead23 - Oct-03-2021 Hello, can someone please explain why when I select a range starting from the end of a string it truncates the last character? I can work from the front end as variable dst will always be the same length but when faced with an unknown string length it would be an issue dst = (r"C:\Users\tekno\Documents\Client Drawings\AAA001") dwg_name = (dst[-7:-1]) print(dst) print(dwg_name) print(dst[40:47]) print(dst[-7:-1]) print(dst[-1])
RE: Last caracter of a string truncated issue when working from the end of the string - deanhystad - Oct-03-2021 Why the parenthesis in the first two lines? They do nothing. Slices work just like the for loop. They start at the start and end just before the end. To slice all the way to the end don't specify an end. dwg_name = dst[-7:]Same goes for slicing from the start. dwg_name = dst[:7] RE: Last caracter of a string truncated issue when working from the end of the string - Yoriz - Oct-03-2021 Rather than [-7:-1] to go to the end [-7:] -7 and the rest. dst = (r"C:\Users\tekno\Documents\Client Drawings\AAA001") dwg_name = dst[-7:] print(dst) print(dwg_name)
RE: Last caracter of a string truncated issue when working from the end of the string - snippsat - Oct-03-2021 Use pathlib then it become much more flexible. >>> import pathlib >>> >>> dst = r"C:\Users\tekno\Documents\Client Drawings\AAA001" >>> folder_last = pathlib.PurePath(dst).name >>> folder_last 'AAA001' >>> >>> # Join would be >>> my_path = pathlib.Path('C:\\') >>> my_path.joinpath(folder_last) WindowsPath('C:/AAA001') >>> pathlib.Path.home().joinpath(folder_last) WindowsPath('C:/Users/Tom/AAA001') |