Question

I'm trying to place two strings together but when I run this code I keep getting an error. I'm sure this is something basic but I ahave been playing with this for 30 minutes and can't figure out what's wrong

filename= 'data.txt'
1output = '1min' + filename
Was it helpful?

Solution

Like most languages, Python does not allow you to create a name that starts with a number. This means that you need to rename 1output because its name is illegal:

output1 = '1min' + filename

Below is a demonstration:

>>> filename = 'data.txt'
>>> 1output = '1min' + filename
  File "<stdin>", line 1
    1output = '1min' + filename
          ^
SyntaxError: invalid syntax
>>>
>>> filename = 'data.txt'
>>> output1 = '1min' + filename
>>> output1
'1mindata.txt'
>>>

When creating names in Python, you must obey the following rules*:

  1. The first character must be either a letter or an underscore.

  2. The rest of the characters must be letters, underscores, and/or numbers.

  3. The finished name cannot be the same as one of the keywords (if, def, for, etc.).


*Note: In addition, you should refrain from creating a name that is the same as one of the built-in functions (str, input, list, etc.). While doing so is legal, it is considered a bad practice by many Python coders (author included). This is because it will overshadow the built-in and thereby make it unusable in the current scope.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top