Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python raw_input messing up string concatenation

I am trying to do something relatively simple in Python and am surprised at how badly this isn't working for how simple it should be.

I'm here just trying to concatenate three simple strings. The input typed at raw_input is "abc" in all cases below:

proj = raw_input("Name of project: ")
print proj
ProjRegex = 'test1' + proj + 'test2'
print ProjRegex

Yields:

abc
test2abc

Case 2

proj = raw_input("Name of project: ")
print proj
ProjRegex = 'test1%stest2' % (proj)
print ProjRegex

Yields:

abc
test2abc

Note that in both cases instead of printing "test1abctest2", as expected, it's substituting test2 for test1.

Then I noticed that if instead of using raw_input at all, if I say:

proj = "abc"
ProjRegex = 'test1' + proj + 'test2'

Then it behaves as expected.

So is something happening in raw_input() that is wanting to do string substitution? My understanding is it takes keyboard input, strips a newline, and returns as a string.

like image 713
Joel Wigton Avatar asked Aug 05 '26 18:08

Joel Wigton


1 Answers

You're running under Windows, correct? The string you enter is terminated by a DOS line ending, so that ProjRegex consists of test1abc\rtest2. When printed, the \r moves the cursor to the beginning of the line, at which point test2 overwrites test1.

like image 84
chepner Avatar answered Aug 07 '26 09:08

chepner