0

Hey guys,

I have been trying to search for this answer on online tutorials, but cannot figure out just what I am doing wrong.

I have a list of names, and some of them have the character '/' For example:

list = [adam, bill, jon/juan]

Because later in my code, I use each name to start a file, this '/' is problematic because it tries to open a new directory. I want the program to search the entries for this character, and if found, delete it. I am trying to use regular expressions:

import re
slash = re.compile("/")

def get_names(file=None):
	infile = open(file)
	Name_List=[]
	for line in infile:
		line = line.strip()
		sline = line.split()
		if sline[10] not in Name_List:
			if not re.match(slash, line):         #NOT WORKING!
 			      Name_List.append(sline[10])	
	return Name_List

I've tried replacing "if not re.match(slash, line)" with "if not re.match(slash, sline[10])" but it is not helping. The code is making new files until it hits one of these problematic list entries, then it just crashes. Any advice?

3
Contributors
6
Replies
7
Views
8 Years
Discussion Span
Last Post by hughesadam_87
0

Because of the slash it gets a little tricky. I have found using split to be more reliable.

name_list = ['adam', 'bill', 'jon/juan']
list_2 = []
for this_name in name_list:
      substrs = this_name.split("/")
      each_name = "".join(substrs)
      print each_name
      list_2.append(each_name)
print "list_2 =", list_2
#
##--------------  or ------------------------------
list_3 = []
for each_name in name_list:
      list_3.append("".join(each_name.split("/")))
print "list_3 =", list_3
0

Your problem is too simple to bother with regex:

mylist = ['adam', 'bill', 'jon/juan']

newlist = [item.replace('/', '') for item in mylist]

print(mylist)   # ['adam', 'bill', 'jon/juan']
print(newlist)  # ['adam', 'bill', 'jonjuan']
0

Would there be an equally easy way to check only one item of the list for a slash, instead of scanning the entire list? Aka,

list = ['hi', 'there', 'friend/family']

Something like

item.replace('/', '') for list[1]

Instead of scanning the whole list, it looks specifically at the line which I know will contain the backslash.

0

Something like

item.replace('/', '') for list[1]

Instead of scanning the whole list, it looks specifically at the line which I know will contain the backslash.

What happened when you tried it?

0

What happened when you tried it?

It was trying to split up the letters in that entry. I figured it out though,

list[1]=list[1].replace("/", " ")

thanks!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.