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?

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

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

Thanks guys, much obliged.

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.

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?

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!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.