KishB87
KishB87

Reputation: 303

Is string initialization necessary in python?

Given this code:

  def double_char(str):
  result = ""
  for i in range(len(str)):
    result += str[i] + str[i]
  return result

Is result = "" the initialization of a string? If so, was it necessary to do in the first place?

Upvotes: 1

Views: 510

Answers (2)

SimonT
SimonT

Reputation: 2359

While Python doesn't require you to state the type of a variable before using it (e.g. int a = 10 instead of just a = 10), it is necessary for the variable result to exist before += can be used with it. Otherwise when you use result += ... Python will try result = result + ....

As another suggestion, avoid naming a variable str since it overwrites the built-in str function/type in Python.

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239623

When you do

result += ...

it basically means that

result = result + ...

Python will not know the value result at this point. So, it will throw this error

UnboundLocalError: local variable 'result' referenced before assignment

Anyway, it is always better to initialize the variables.

Suggestions

  1. Don't use str as a variable name, it hides the builtin str function.

  2. What you are trying to do, can be done in a single line, like this

    return "".join(i*2 for i in input_string)
    

def double_char(input_string):
  return "".join(i*2 for i in input_string)

print double_char("thefourtheye")           # tthheeffoouurrtthheeyyee

Upvotes: 7

Related Questions