I copied this code from page 11 of
http://personal.denison.edu/~krone/cs173/files/PythontoC++.pdf
and assigned it to a Python string.

Alas there are still line numbers. How could I use Python to remove these? Help, I have a mental block.

s = '''
1 #include <iostream>
2 using namespace std;
3
4 int gcd(int u, int v) {
5 int r;
6 while (v != 0) {
7 r = u % v; // compute remainder
8 u = v;
9 v = r;
10 }
11 return u;
12 }
13
14 int main( ) {
15 int a, b;
16 cout << "Enter first number: ";
17 cin >> a;
18 cout << "Enter second number: ";
19 cin >> b;
20 cout << "The gcd is " << gcd(a,b) << endl;
21 return 0;
22 }
'''

You can try something along the line of

ss = re.sub(r'^\d+ ?', '', s, re.MULTILINE)

Another option ...

# remove_line_numbers102.py

# copied from
# http://personal.denison.edu/~krone/cs173/files/PythontoC++.pdf
# page 11
s = '''
1 #include <iostream>
2 using namespace std;
3
4 int gcd(int u, int v) {
5 int r;
6 while (v != 0) {
7 r = u % v; // compute remainder
8 u = v;
9 v = r;
10 }
11 return u;
12 }
13
14 int main( ) {
15 int a, b;
16 cout << "Enter first number: ";
17 cin >> a;
18 cout << "Enter second number: ";
19 cin >> b;
20 cout << "The gcd is " << gcd(a,b) << endl;
21 return 0;
22 }
'''

new_str = ""
for line in s.split('\n'):
    try:
        while line[0].isdigit():
            line = line[1:]
    except IndexError:
        pass
    new_str += line.strip() + '\n'

print(new_str)

''' my result -->
#include <iostream>
using namespace std;

int gcd(int u, int v) {
int r;
while (v != 0) {
r = u % v; // compute remainder
u = v;
v = r;
}
return u;
}

int main( ) {
int a, b;
cout << "Enter first number: ";
cin >> a;
cout << "Enter second number: ";
cin >> b;
cout << "The gcd is " << gcd(a,b) << endl;
return 0;
}
'''
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.