0

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

Edited by HiHe

3
Contributors
2
Replies
28
Views
2 Years
Discussion Span
Last Post by vegaseat
1

You can try something along the line of

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

Edited by Gribouillis

0

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;
}
'''
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.