-4

So i have this small piece of code which just wont work:

 while c<b:
     str2 += str1[c]
     c+=1

print str2

b is the length of str1 that i want to copy to str2, and c is the point which i want to begin transfer from str1, then the while loop is just supposed to transfer all the characters from str1 to str2.

For some reason i can't seem to print str2 and get this error message:

"NameError: name 'str2' is not defined"

My guess is that I'm just doing something simple wrong, I just began experimenting with Python and have only really done C# before.

4 Answers4

4

A better approach would be to slice the strings:

str2 = str1[c:b]

This copies str1 from character number c and up to character number b into str2.

For example:

>>> 'Hello World'[3:7]
'lo W'

Here's a little information about Python's slice notation: Explain Python's slice notation

Community
  • 1
  • 1
Blender
  • 289,723
  • 53
  • 439
  • 496
2

You have to initialize str2:

str2 = ''
while c<b:
    str2 += str1[c]
    c+=1

print str2

Or else do a function that receives str2 as parameter:

def myfunc(str2=''):
    while c<b:
        str2 += str1[c]
        c+=1

    return str2

where str2 parameter is by default initialized as '', i.e. empty string.

Joseph Victor Zammit
  • 14,760
  • 10
  • 76
  • 102
  • Yep this does it. I was a bit confused a while with Python not accepting things such as "string" or "int" but this fixed my problem. Thanks very much. – user1577913 Aug 05 '12 at 23:17
0

With

str2 += str1[c]

You are saying, "please add str1[c]" to whatever is already in str2 .. the problem is that you haven't initialized str2 with anything (at least in the code you show).

Easiest fix is to give str2 an initial value before you use it in the loop, e.g., str2=''

Levon
  • 138,105
  • 33
  • 200
  • 191
0

Why not to use something in the lines of:

str2 = str1[c:]
favoretti
  • 29,299
  • 4
  • 48
  • 61