d5e5 109 Master Poster
#!/usr/bin/env python
import re
DataDir = '/home/david/Programming/Python'
phonefile = DataDir + '/' + 'PhoneNumbers.txt'

"""Read each line from file. If it starts with
a string of exactly 10 consecutive digits, assume
this is a phone number and print it."""

ph_nbr_pattern =  r'^(\d{10})(?:\s|$)'
compile_obj = re.compile(ph_nbr_pattern)

file2read = open(phonefile, 'r')
for currentline in file2read:
    match_obj = compile_obj.search(currentline)
    if match_obj:
        print currentline.rstrip()
    
file2read.close()
"""Output is:
4616186224
3501292628
2698109000
4398248508
8462632398
5414846117
9167449701
5097458418
"""
d5e5 109 Master Poster

Why not do it as follows? my ($oct1, $oct2, $oct3, $oct4) = ($1, $2, $3, $4); After all, you wrote the regular expression, so you know it returns four matched groups. The sites you googled may be addressing the situation where programmers don't know how many data items they may need to save and so are thinking of creating variable names dynamically at runtime. In those situations, you can use hashes instead of scalar variables. Here is a quote from Beginning Perl which may be saying something similar to what you've been reading about using hashes instead of creating variables on-the-fly.

d5e5 109 Master Poster

Thanks tonyjv for the clarification and the test data.

#!/usr/bin/env python
import re
def FindName(name,list1):
    """ searches for a pattern in the list, returns the complete list entry(s)
    as a string. Is case sensitive.
    """
    mlist = []
    pattern = r"""^(%s.*)$""" % (name)
    for item in list1:
        match = re.search(pattern, item)
        if match:
            mlist.append(match.group())
        
    if len(mlist) > 0:
        return ', '.join(mlist)
    else:
        return 'Fail ' + name

            
china=['In', 'China', 'people', 'teach',"Confusius's",
       'teachings','dilligently.','Those',"Confusius''s",
       'teachings','are','called','Taoism.']

this='Conf'

print FindName(this,china)

print [(i,x) for (i,x) in enumerate(china) if x.startswith(this)]

"""Output:
Confusius's, Confusius''s
[(4, "Confusius's"), (8, "Confusius''s")]
"""
d5e5 109 Master Poster

if ($record =~ m/BUNP:\s*(.*)$/) { #Allow optional space, then capture to end of line

d5e5 109 Master Poster

If you use findall instead of search you get a list of strings.

>>> import re
>>> MyStr = "<test>some text here</test> <other> more text </other> <test> even more text</test>"
>>> m=re.compile('<test>(.*?)</test>', re.DOTALL).findall(MyStr)
>>> print m
['some text here', ' even more text']
>>>

Sounds like that will definitely help down the road, but it still didn't work in this case:

>>> import re
>>> MyStr = "<test>some text here</test> <other> more text </other> <test> even more text</test>"
>>> m=re.compile('<test>(.*?)</test>', re.DOTALL).search(MyStr)
>>> print m.group(1)
some text here
>>> print m.group(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: no such group

Dave

d5e5 109 Master Poster

Not sure if you intended to allow a space between the colon and $v or not. Assuming not, the following should work.

#!/usr/bin/perl
#Regex.pl
use 5.006;
use strict;
use warnings;

#Assign some values to variables and build request string
my $k = 'kryptonite';
my $v = 'valium';
my $valid = 1;
my $request = "RemoveAcc $k:$v";# <----No space allowed between : and $v, right?
print "request is $request\n";
if ($valid and ($request =~ m/RemoveAcc\s*(\w+):(\w+)/)){
	my $first = $1;
	my $second = $2;
	print "First value is $first\nSecond value is $second\n";
} else {
	print "Not valid or doesn't match\n";
}
samready commented: thanks that did it. (you're right, the space wasn't supposed to be there, but i put it there so it didn't make a smiley :$" +0
d5e5 109 Master Poster

Do you have a package manager? If you have ActivePerl from ActiveState then you probably have PPM. Just type ppm at the command prompt and PPM starts up with a GUI. I don't know if that will solve the problem, but package managers are an alternative way to install binaries while automatically notifying you of dependencies (if any).

d5e5 109 Master Poster

Hi d5e5, it works for me finally except that writing into the file is still troublesome. I can't understand why this is so as it works for you guys both by writing into the file and onto the cmd.
Thanks

Does it work if you remove the '+' from the statement opening the DATA file? Try open (DATA,">react_out.txt") or die "Can't open data"; instead of open (DATA,"+>react_out.txt") or die "Can't open data"; As I said, the original worked for me without removing the '+' but you may have a different version of Perl or a different operating system. I've never used the +>filename before. It supposedly lets you read and write to the file, instead of just reading, but your script does not read from the DATA file anyway, so you don't need the '+'. I don't know if this will help... just guessing.

d5e5 109 Master Poster

I tried Murtan's version (posted yesterday March 8) of the script. Here's how it looked when I ran it in Terminal:

david@david-laptop:~$ cd /home/david/Programming/Perl
david@david-laptop:~/Programming/Perl$ perl SearchFile.pl
Enter reaction name for searching:A1_HTTT24
Enter reaction name for searching:B3_PGAI1
Enter reaction name for searching:
Given Key isn't found in the file
david@david-laptop:~/Programming/Perl$

This created the data.txt file and here are the contents:

A1_HTTT24,GLUC_ext = GLUC 
B3_PGAI1,GLUC6P = FRUC6P

I don't know why the script wouldn't work for you, Perly. Are you sure you entered the keys correctly during the test? It has to be upper case because 'A1_HTTT24' does not equal 'a1_httt24'.

d5e5 109 Master Poster

Convert the string into a list of characters. Convert the list into a set whose members are unique characters in the list. Then print the length of this set.

>>> str1 = "abcdeb";
>>> str1
'abcdeb'
>>> charset = set(list(str1))
>>> len(charset)
5
d5e5 109 Master Poster
#!/usr/bin/env python
allthepoem = open ("c:\users\david\programming\python\poem.txt", "U").read()
allthepoem_upper_case = allthepoem.upper()
charslist = list(allthepoem_upper_case)
my_dict = dict()
for char in charslist:
    if ord(char) < 33: # space is chr(32), chr(10) is linefeed, chr(13) is carriage return, etc.
        char = "chr(" + str(ord(char)) + ")"
    if char in my_dict:
        my_dict[char] += 1
    else:
        my_dict[char] = 1
    
for char in my_dict:
    print char, " occurs ", my_dict[char], " times"
d5e5 109 Master Poster

Would 'Aa' count as A----2 or

A----1
a----1

?

d5e5 109 Master Poster

Ok, but I need to do this for an arbitrary number of file names. Is there any way to completely remove the first element in the array and make the file path the first element?

Create an empty list and append what you want from sys.argv into your list.

import sys

# there is a commandline
if len(sys.argv) > 1:
    arglist = []
    # sys.argv[0] is the program filename, slice it off
    for arg in sys.argv[1:]: #Slice of sys.argv starting at sys.argv[1] up to and including the end
        arglist.append(arg)
else:
    print "usage %s arg1 arg2 [arg3 ...]" % sys.argv[0]
    sys.exit(1)

# if the arguments were This.txt That.txt Other.log
# arglist should be ['This.txt', 'That.txt', 'Other.log']
print(arglist)
vegaseat commented: nice +10
d5e5 109 Master Poster

Good answer but permit me to suggest a minor change to the above example.

#!/usr/bin/env python
#argecho.py
import sys
if sys.argv:
    print "The name of this program is:",sys.argv[0]
    print "The first command line argument I received is:",sys.argv[1]
    print "The second command line argument I received is:",sys.argv[2]
lllllIllIlllI commented: Woops :) my bad. Nicely done +2
d5e5 109 Master Poster

I put your sample data into a file called PhoneNbrs.txt in the same directory where I wrote the following script:

#!/usr/bin/perl
use strict;
use warnings;
my $phones = "PhoneNbrs.txt";
my $phones_errors = "PhoneNbrsErrors.txt";
open (FIN, '<', $phones); #Open file for reading
my $header = <FIN>; #Read first record of file to get past it.
open (FOUT, '>', $phones_errors); #Open file for writing
while (<FIN>) { #Read each remaining record into $_ variable, one at a time
    if ($_ =~ m/,\s*\d\d\d-\d\d\d\d\s*$/) { #If the current record matches valid number pattern
        next # Go to the top of the loop to read the next record (skip this one)
    }
    else {
        print FOUT; #Write this record into output file
    }
}
print "Done. Look in $phones_errors for errors (if any).\n";
close FIN;
close FOUT;
d5e5 109 Master Poster

I don't have a script that does it but if you create and show us an example with a few correct and incorrect phone numbers I'm sure somebody could help you make a script that prints all the correct and / or the incorrect lines separately.

We need to know if your file has a header line at the start, whether the names are enclosed in quotes, etc. Not all csv files are formatted the same. Microsoft Excel creates them one way but other programs vary the format a bit. I understand you don't want to give us real names and numbers, but if you can make up a few it will give us something to test.

d5e5 109 Master Poster

Call the findall method instead of search to get an array of matches.

def matchmyip(line):
    if ippattern.search(line):
        print ippattern.findall(line)

import re
ippattern = re.compile(r"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b")

if __name__ == "__main__":
    s = "1999-08-01 00:00:00 212.67.129.225 - W3SVC3 PROWWW01 194.128.73.195 GET /entrance/V0_1/default.asp bhcd2=933465599 302 0 497 396 15 80 HTTP/1.1 Mozilla/4.0+(compatible;+MSIE+4.01;+Windows+95;+FREESERVE_IE4) bhCookie=1;+ASPSESSIONIDGGGGGRDN=PPLCJMKDDJBMPIMEAEDPIJGF -"
    matchmyip(s)
d5e5 109 Master Poster
#!/usr/bin/perl -w
use strict;
my $string = "#324423asdd asd 'BecamePosters' ";
if($string =~ m/('[a-zA-Z]{1,40}')/) { #Put parentheses around what should be $1
print "ok!\n";
print $1;
} else {
print "not ok!\n";
}
d5e5 109 Master Poster

I realize your question is about object creation and use, about which I know little, but permit me to add an FYI about navigator.appName:

When I tested Airshow's code in my browser (Chrome) I noticed that the property you are testing, navigator.appName returns 'Netscape' when run in Chrome. I don't know why, but googled it and found that navigator.appName returns 'Netscape' in Safari and Firefox as well (see http://code.google.com/p/doctype/wiki/NavigatorAppNameProperty). You will have to test some property other than navigator.appName to detect browsers other than Microsoft Internet Explorer and Opera.

d5e5 109 Master Poster

You're welcome. I neglected to say the test worked for me only after I changed the '==' operator to 'eq' as ItecKid pointed out. Also, I recommend using the strict module in any Perl script -- just add use strict; -- unless you have a particular reason not to use it. It warns you of unused or misspelled variable names, etc.

d5e5 109 Master Poster

I don't have bash but when I tested your Perl script from the Windows command line (after copying an html file into the current directory it worked -- until it died because I don't have a readFile subroutine. But the point is that I didn't get the "$0: no existing file available for parsing" message on my platform. It's a mystery.

Remember that naming variables in Perl is case-sensitive. I see you have variables named "$htmlFile" and "$htmlfile" in your program, but I don't see how that would cause this particular error.

d5e5 109 Master Poster

In that regex for illegal characters I should not have put the \g modifier at the end. As soon as we find the first illegal character that is all we need to know. The /g global modifier attempts to match all illegal characters in the string starting at the position where it previously found a match. All we need to know is whether there is at least one illegal character in the string so we don't need /g and it is somehow giving us inconsistent results.

In your script, try replacing the regex like this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd"
    >
<html lang="en">
<head>
    <title>Test regex punctuation filter</title>
    
<script type="text/javascript">
function checkString (strng) {
    var error = false;
//var illegalChars = /[\u0021-\u002f\u003a-\u0040\u005b-\u005e\u0060\u007b-\u007e]/g; // The /g (for global) is a goof.
    var illegalChars = /[\u0021-\u002f\u003a-\u0040\u005b-\u005e\u0060\u007b-\u007e]/; // NOT global.
    error = (illegalChars.test(strng));
return error;
}

// The following lines test the function with a string containing illegal chars.
var teststring = "Java$cript"; //Illegal character. Test should return 'true'
var errmsg = checkString(teststring);
document.writeln("Testing \"<b>" + teststring + "</b>\" results in <b>" + errmsg + "</b><p>");
var teststring = "Javascript"; //No illegal character. Test should return 'false'
var errmsg = checkString(teststring);
document.writeln("Testing \"<b>" + teststring + "</b>\" results in <b>" + errmsg + "</b><p>");
</script>

</head>
<body>

</body>
</html>
Venom Rush commented: Thanks for your help ;) +3
d5e5 109 Master Poster

I simplified my test script. It still seems to find illegal characters wherever they are in the test string.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd"
    >
<html lang="en">
<head>
    <title>Test regex punctuation filter</title>
    
<script type="text/javascript">
function checkString (strng) {
    var error = false;
    var illegalChars = /[\u0021-\u002f\u003a-\u0040\u005b-\u005e\u0060\u007b-\u007e]/g; // Don't allow any of these
    error = (illegalChars.test(strng));
return error;
}

// The following lines test the function with a string containing illegal chars.
var teststring = "Here is a str&ing with illegal characters";
var errmsg = checkString(teststring);
document.writeln("Testing \"<b>" + teststring + "</b>\" results in <b>" + errmsg + "</b><p>");
var teststring = "Here is a string without any illegal characters";
var errmsg = checkString(teststring);
document.writeln("Testing \"<b>" + teststring + "</b>\" results in <b>" + errmsg + "</b><p>");
</script>

</head>
<body>
</body>
</html>
d5e5 109 Master Poster

...the 'illegal' characters are only detected if they are the first or last letter. If it's anywhere between valid characters it goes undetected.

That's strange, I can't duplicate the problem. Here is the test script I'm using. Can you give me an example to put in the teststring variable that results in undetected illegal characters?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd"
    >
<html lang="en">
<head>
    <title>Test regex punctuation filter</title>
    
<script type="text/javascript">
function checkName (strng) {
    var error = "";
    var illegalChars = /[\u0021-\u002f\u003a-\u0040\u005b-\u005e\u0060\u007b-\u007e]/g; // Don't allow any of these
    if (strng == "") {
   	error = "Please enter your name.\n";
    }
    else if((strng.length < 2)) {
    	error = "The name is the wrong length.\n";
    }
    else if (illegalChars.test(strng)) {
    	error = "The name contains illegal characters.\n";
    }
return error;
}

// The following lines test the function with a string containing illegal chars.
var teststring = "Here is a string with ill:egal ch@racters";
var errmsg = checkName(teststring);
//alert("Testing \'" + teststring + "\' results in \'" + errmsg + "\'");
document.writeln("Testing <p><b>" + teststring + "</b><p> results in <p><b>" + errmsg);
</script>

</head>
<body>

</body>
</html>
d5e5 109 Master Poster

Try the following character class: var illegalChars = /[\u0021-\u002f\u003a-\u0040\u005b-\u005e\u0060\u007b-\u007e]/g; // Don't allow any of these Javascript supports specifying unicode characters by hexadecimal expressions like \u0060 and ranges like \u007b-\u007e .

There is a fun website at http://hamstersoup.com/javascript/regexp_character_class_tester.html that gives you the unicode expressions for any character class you specify.

d5e5 109 Master Poster

final = reorder(a, b)

Look at line 18 of your first example, where you test your first function. Variables a and b have meaning only in your function. You need to pass the variables first_str and second_str when you call your function, not a and b, which are out of scope until control is passed to your function.

for i in range(len(reorder_str)):

Also look at the for loop in your first function. It loops through a range of 0 up to the length of reorder_str. The strings in variables a and b each have length of 3, so what happens when variable i = 4? a[4] and b[4] are undefined.

d5e5 109 Master Poster

One more suggestion: if you still want to use the RegEx pattern that specifies each punctuation character you want to remove, try preceding the " and the ' characters with a backslash in the RegEx pattern, like this: var myRegExPattern = /[\-,?~!@#$%&*+\-\'=\"]/g On my platform it doesn't make any difference, it matches and replaces the quotes either way, but might as well try it. (Notice that I had to escape the hyphen - character because otherwise it has a special meaning in RegEx character classes.)

Good luck. I'm learning about javascript today by looking at the tutorial at http://www.w3schools.com/js/default.asp. Their "Try It Yourself" button is handy for testing something quickly.

d5e5 109 Master Poster

That's strange. I tested the following and the same RegEx did remove my single and double quotes. I modified the script so you can type in any text you want in the prompt box.

<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">

<!-- Hide from browsers that do not support JavaScript
var myRegExPattern = /[\-,?~!@#$%&*+\-'="]/g
var query = "Let's test to see if 'single quotes' and \"double quotes\" are removed.";
query = prompt("Please enter your query",query);
var cleanquery = query.replace(myRegExPattern, "");
alert("Cleaned query is: " + cleanquery);

document.writeln("Original query was:<br>")
document.writeln(query)
document.writeln("<p></p>")
document.writeln("Cleaned query is:<br>")
document.writeln(cleanquery)

// --> Finish hiding

</SCRIPT>

I'm testing on a Windows Vista system with regional settings for North America. If you are using a different platform with different regional settings maybe that would give you different results.
Would it be simpler to make a RegEx pattern for the characters that you do want in your query? If you want only alphanumeric characters and spaces in your query you could make a Regex to find any character not in the specified character set. For example:

<HTML>
<HEAD>
<TITLE>Testing RegEx in Javascript</TITLE>
<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">

<!-- Hide from browsers that do not support JavaScript
var myRegExPattern = /[^\w\s]/g
var query = "Let's test to see if 'single quotes' and \"double quotes\" are removed.";
query = prompt("Please enter your query",query);
var cleanquery = query.replace(myRegExPattern, "");
alert("Cleaned query is: " + cleanquery);

document.writeln("Original query was:<br>")
document.writeln(query)
document.writeln("<p></p>")
document.writeln("Cleaned query is:<br>")
document.writeln(cleanquery)

// --> Finish hiding

</SCRIPT>
</HEAD>

<BODY>
<p> HTLM body …
d5e5 109 Master Poster

You can create a regular expression like the one in the variable called myRegExPattern to match any character listed between the square brackets. The square brackets define a "character class" aka "character set". Then replace each character that is matched.

<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
<!-- Hide from browsers that do not support JavaScript
var myRegExPattern = /[\-,?~!@#$%&*+\-'="]/g
var query = "Then it's one, two, three strikes you're out at the old, ball-game!..."
query = query.replace(myRegExPattern, "");
document.writeln(query)
// --> Finish hiding
</SCRIPT>
d5e5 109 Master Poster

Please try the following as well. It works on my computer now.

#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import os, sys
#DictManipulation.py written 26/09/09
#See flow_dia_for_new_dict.ods, this directory
#
# A text file that is an English to Greek  dictionary and has 2 columns. 
# As there are many entries it takes up 25 or so pages. The object is to 
# produce a file that has 2 x 2 columns and so producing half the number 
# of pages. The 2nd columb generated should be the next 72 entries following
# the first column so the alfa order is maintained.
# 
# A sample of the original file is shown below
#
#August                    Αύγουστος (ο)                        
#aunt                      θεία  η                              
#autumn                    φθινόπωρο (το)                       
#bad, ugly (adj.)          άσχημος, -η, -ο                      
#bad, wicked, evil (adj.)  κακός, -ή, -ό                        
#bank                      τράπεζα (η)                          
#basket                    καλάθι (το)     

def rpad (orig_string, length):
    """Adds spaces to the end of a string until it has the desired length"""
    #Convert to unicode utf-8 because if your default encoding is Ascii the encode step fails
    ustring = unicode(orig_string,"utf-8","strict")
    #In a plain string Greek symbols have length = 1 instead of 2
    plain_string = ustring.encode("cp737", "replace")
    spaces_needed = length - len(plain_string)
    padded_string = orig_string + " " * spaces_needed
    return padded_string

lines_per_page = 73       
current_page  = 0       
line_pointer_a = 1        
line_pointer_b = line_pointer_a + lines_per_page 

write_file = open ("newDict.txt", "w")
read_file = open ("origDict.txt", "r")
lines_in_file = read_file.readlines ()
read_file.close()
lengh_file = len (lines_in_file)
new_line = '\n'


while line_pointer_a != (lines_per_page …
chico2009 commented: of great assistance thanks +1
d5e5 109 Master Poster

Now that we can recreate the problem I'm confident that we're close to finding a way around it. I just need to learn a little more about how to format a unicode string. Maybe something to do with encoding or decoding it to set the length we want when formatting.

I'll try to look at it some more this afternoon, unless someone else finds the answer before then.

d5e5 109 Master Poster

No solution yet. Now it's driving me crazy.:)
What I think is happening is that Python knows how to read your input file and write to your output file even though there are non-Ascii characters represented in them because the # -*- coding: utf-8 -*- statement informs it. However when I examine the contents of lineA using Idle, it shows me that it has content like the following:

>>> lineA
'2                             \xce\xb4\xcf\x8d\xce\xbf (also \xce\xb4\xcf\x85\xce\xbf)'
>>> 
>>> len(lineA)
50
>>> lineB
'but                           \xce\xbc\xce\xb1'
>>> len(lineB)
34
>>> #...So when we adjust the widths of lineA and lineB, it is the above unicode sequences we are manipulating
>>> combined_AB = "%-56s%-60s" % (lineA,lineB)
>>> combined_AB
'2                             \xce\xb4\xcf\x8d\xce\xbf (also \xce\xb4\xcf\x85\xce\xbf)      but                           \xce\xbc\xce\xb1                          '
>>> len(combined_AB)
116
>>> #You see the problem? Python does the length adjusting BEFORE it converts the unicode sequence into the record that it writes to the output file.
d5e5 109 Master Poster

Thanks Chico2009. I'm interested because here in Canada we have two official languages so it's good to learn how this encoding thing works. I just tried testing something in Python's Idle and it complained right away about "unsupported characters".
I have to go to lunch now but I'll look at your attachment later this afternoon if possible.

d5e5 109 Master Poster

If I understand correctly, the above shows 14 examples of output records -- that is, 14 examples of the contents of newString after the newString = '%-30s%-30s%s' % ( lineA , lineB, new_line) runs.

What I'd like to do is run that command myself to reproduce your output and try to modify the command to avoid the irregular-looking output.

Could you show us one or two examples of the initial contents of the lineA, lineB, and new_line variables? I'm a Python beginner as well so I don't know all the answers, but I think if we knew some sample values for the input variables we would have something to test.

d5e5 109 Master Poster

I can't see where the columns are in your example because this website reduces multiple spaces to single spaces. If you wrap your example in code tags (click the "Help with Code Tags" link for instructions) we can see how your example data really is appearing to you.

For example, when I type:
'This is lineA This is lineB' without the code tags you can't see the 20 spaces that I typed between 'lineA' and 'This'.

With the code tags, the same example looks like this:

'This is lineA       This is lineB'
d5e5 109 Master Poster

Blank lines won't make any difference to how the program runs. Since I'm new to Perl I probably don't have a good sense of style yet. But I was trying to separate my code into three sections: introductory lines that appear in all programs, followed by setting up and printing the test string, followed by modifying and printing the resulting string.

d5e5 109 Master Poster

Sorry, I read your example wrong. This should do it. Too bad the substitute command uses slashes to delimit the two strings. It confuses me, but it should work this time.

#!/usr/bin/perl -w
#ReplaceSlashWithBackslash.pl
use strict;

my $myPath = 'c:/perl/test'; # Example string containing backslashes
print "\nOriginal string is: $myPath\n\n";

# The following command replaces forward slashes with backslashes
# You need to escape the backslash and slash with backslashes
$myPath =~ s/\//\\/g; #There must be a better way, but I don't know it.
print "Modified string is: $myPath\n";
d5e5 109 Master Poster
#!/usr/bin/perl -w
#ReplaceBackslashWithSlash.pl
use strict;

my $myPath = 'c:\perl\test'; # Example string containing backslashes
print "\nOriginal string is: $myPath\n\n";

# The following command substitutes backslashes with forward slashes
# You need to escape the backslash and slash with backslash
$myPath =~ s/\\/\//g;
print "Modified string is: $myPath\n";
d5e5 109 Master Poster

Instead of trying to make up new incremented variable names on the fly, you can create an empty list and append each intFCITC value to it. The elements of a list are sequenced in the order in which they were appended and can be referred to by index. The first element appended to the list has index of zero.

noline=0
intFCITC_list = [] #Empty list where we will put all values of intFCITC
for line in open("fcitc.txt"):
    if noline==1:
        fcitc=line[:9].strip()
        intFCITC = int(float(fcitc)) #OP wants this to be integer.
        intFCITC_list.append(intFCITC)
        limConst=line[29:79].strip()
        noline+=1
    elif noline==2:
        contDesc=line[90:137].strip() #Added subscripts. Don't want entire line.
        print fcitc
        print limConst
        print contDesc
        noline=0
    if "FCITC" in line:
        noline+=1
print "\nList of intFCITC values:" #All the intFCITC values should be in intFCITC_list
print intFCITC_list

#Refer to any element by its index
print "intFCITC_list[0] = ", intFCITC_list[0] #the first one is FMPP to FPL
print "intFCITC_list[1] = ", intFCITC_list[1] #the second one is FMPP ro PEF
print "intFCITC_list[2] = ", intFCITC_list[2] #FMPP to TECO?
d5e5 109 Master Poster
if coursenum in courselistA:  #courselistA is the set of course numbers
       #Convert courselistA into a list and use list comprehension
       print [x for x in list(courselistA) if x > coursenum]
d5e5 109 Master Poster

jice's solution looks good to me, unless you want only a slice of the second data line and want to convert the FCITC string into an integer. Here it is with a couple of minor changes to do that.

noline=0
for line in open("fcitc.txt"):
    if noline==1:
        fcitc=line[:9].strip()
        intFCITC = int(float(fcitc)) #OP wants this to be integer.
        limConst=line[29:79].strip()
        noline+=1
    elif noline==2:
        contDesc=line[90:137].strip() #Slice from line 2. Don't want entire line.
        print intFCITC
        print limConst
        print contDesc
        noline=0
    if "FCITC" in line:
        noline+=1
d5e5 109 Master Poster

The above needs another element at the end of the list so it will handle a perfect score of 100%. I modified the program to test all possible values. It's still not elegant.

def CalcGrade(grade):
    """Converts a numeric grade between 0 and 100 into a letter between 'A' and 'F' """
    index = int(grade)/10

    #Added another "A" to grades list to handle perfect grade of 100
    grades = ["F", "F", "F", "F", "F", "F", "D", "C", "B", "A", "A"]
    final = grades[int(index)]
    return final

#grade = raw_input("Enter the student's grade: ")
# Commented out the raw input and used loop to test all values
for x in range(101): #Test for values between 0 and 100
    print x, " Converts to ", CalcGrade(x)
d5e5 109 Master Poster

I think you can use pretty much the same list that you used for the simpler problem. All you need to come up with is a formula to calculate the index for each grade.

def main():
    grade = raw_input("Enter the student's grade: ")
    index = int(grade)/10
    grades = ["F", "F", "F", "F", "F", "F", "D", "C", "B", "A"]
    final = grades[int(index)]
    print final

main()