LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Python - Concatenating a String With a Variable (https://www.linuxquestions.org/questions/programming-9/python-concatenating-a-string-with-a-variable-4175620387/)

killingthemonkey 12-27-2017 12:17 PM

Python - Concatenating a String With a Variable
 
Code:

listOfStrings = [ "Hello"
                  "World"
                  "Where"
                  "have"
                  "you"
                  "been"]
                                                 
for i in range(len(listOfStrings)):
    print(listOfStrings[i].upper() + "\n")

My output:
Code:

HELLOWORLDWHEREHAVEYOUBEEN
Can someone please tell me why the newline isn't being output?

Thank you for your help.

dugan 12-27-2017 12:35 PM

Because Python, like C, automatically concatentates strings that are separated only by whitespace.

For a list of strings, you need commas.

Code:

["a", "b", "c"]

killingthemonkey 12-27-2017 12:41 PM

dugan,
Thank you! If I'm not mistaken, the book I'm working through advised me that they needed to be separated by commas. Should have been blatantly obvious. Actually, I guess it was to you. To me? Not so much.

Sefyir 12-28-2017 11:21 AM

Quote:

Originally Posted by killingthemonkey (Post 5798431)
Code:

for i in range(len(listOfStrings)):
    print(listOfStrings[i].upper() + "\n")


Also, the range / len / indexing isn't needed

Code:

listOfStrings = [ "Hello",
                  "World",                 
                  "Where",
                  "have",
                  "you",
                  "been"]

Code:

for i in range(len(listOfStrings)):
    print(listOfStrings[i].upper() + "\n")

Code:

for i in listOfStrings:
  print(i.upper() + '\n')


pan64 12-28-2017 11:35 AM

Code:

print "\n".join(listOfStrings).upper()


All times are GMT -5. The time now is 03:43 PM.