#🔒 Trying to keep tuples intact when typecasting

10 messages · Page 1 of 1 (latest)

outer vapor
#

I have a text file that contains list of files, example line: "drwx------ 8 foo bar-all 4096 Dec 27 13:55 .git"
The regex is correct and findall works as expected. The var ´matches´ is a list of tuples that have strings representing numbers and other strings inside them.
How can I typecast all the strings representing numbers to integers without losing the tuples?
The below code returns a list with the tuples no longer there 😦

#!/usr/bin/env python3

import re


def file_listing(filename="src/listing.txt"):
    with open(filename, "r") as file:
        contents = file.read()
        pattern = (
            r"([\d]*)\s([A-Z][a-z]+)\s([\d]+)\s([\d]+)\:([\d]+)\s(.[a-z]*[.]?[a-z]*)"
        )
        matches = re.findall(pattern, contents)
        print(matches) # [('2356', 'Dec', '11', '11', '50', 'add'), ('164519', 'Dec', '28', '17', '59', 'basics.ipynb')]
        return [(int(j) if j.isdigit() else j) for i in matches for j in i]


def main():
    print(file_listing("src/listing.txt"))


if __name__ == "__main__":
    main()

agile sunBOT
#

@outer vapor

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

minor prism
#

Nevermind

#

I was thinking you had for in the () part, but you don't. You'll still need to use the above though to create tuples in your nested list comprehension.

#

I think tuple(int(j) if j.isdigit() else j for j in i) as the inner expression should do the trick

outer vapor
#

Would you look at that, it works with that. Thanks a lot mate

#

!close

agile sunBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.