read a file that contains random characters and digits as name and separate each character and digit in python

To read a file containing randomly placed characters and digits and separate them, we need to follow these steps:

  1. Open the file in read mode using open() function.
  2. Read the contents of the file using .read() function.
  3. Loop through each character in the contents of the file.
  4. Check if it's a character or digit using isalpha() and isdigit() functions.
  5. Append the character or digit in separate lists for characters and digits.
  6. Join the individual characters and digits back to form the original name.

Here's the code snippet that demonstrates this:

main.py
# opening file in read mode
file = open("filename.txt", "r")

name = file.read()  # reading the contents of the file

# creating empty lists
characters = []
digits = []

# looping through each character of the name
for char in name:
    if char.isalpha():  # checking if character is an alphabet
        characters.append(char)  # appending the character to characters list
    elif char.isdigit():  # checking if character is a digit
        digits.append(char)   # appending the digit to digits list

# Joining the individual characters and digits back to form the original name
name_separated = "".join(characters + digits)

print(name_separated) # printing the name with characters and digits separated
file.close()   # closing the file
741 chars
22 lines

gistlibby LogSnag