Concatenated strings

edited February 2011 in General Chat
Hey there, I'm learning the python program language from a book, and I'm on a section explaining concatenated strings. I understand how to do them, but I can't see why you'd want to use them! Can anyone explain where and why you'd use one? Thanks!
print ("This string " + "is concatenated!")

Comments

  • edited February 2011
    I tend to use them if I want to show the contents of a variable in a single message line.
  • edited February 2011
    I tend to use them if I want to show the contents of a variable in a single message line.

    I see, could you give a short example? I'm fairly new to python :)
  • edited February 2011
    My example is in C# as that's what I've been playing with most recently, but it should still be relevant.

    Assuming that the variables userName & date were declared both as a string and that the program asked the user to enter their name and it was stored in userName (the date would be retrieved by an automatic call) then they could be use to simplify the output of the data in a nice clean fashion using code like this:
    string str = "Hello " + userName + ". Today is " + date + ".";
    

    That code would store "Hello name. Today is date." which could be displayed with ease or even added to like this:
    string str += " How are you today?";
    

    Do you get what I mean?

    The example you gave isn't a good use of it, as it's the same as just typing the whole sentence inside the quotes but it does demonstrate what it does.
  • edited February 2011
    String concatenation is quite useful in many programming languages.

    For Python, (as mentioned above), being able to concatenate two string variables can come quite in handy.

    Here's some examples:
    s1 = "Hello"
    print s1 + "World"
    # HelloWorld
    print s1,"World"
    # Hello World - The , is rendered as a space
    print s1+s1
    # HelloHello
    
    # Prints all the lines of the file 'textfile', each prefixed by "Hello"
    f = open('textfile', 'r')
    for line in f.readlines():
        print "Hello", line
    f.close()
    
    games = ['Bone', 'Sam and Max', 'SBCG4AP', 'Wallace and Gromit', 'Monkey Island', 'Back to the Future', 'Puzzle Agent'] # list of strings
    for i in range(0,len(games):
        print "%d: %s" % (i, games[i])
    
    # This will print out:
    # 0: Bone
    # 1: Sam and Max
    # 2: SBCG4AP
    # 3: Wallace and Gromit
    # etc.
    

    I've only been working in Python for about six months (but C/C++ for 10 years before that, plus shell scripting, perl and other bits and pieces) and I love it. Python is quite a great language to work with.

    Feel free to try out all of the above. The good thing about Python is you can run the interactive python console and try things out, without having to first write the whole thing up in a text file and compile it.
  • edited February 2011
    Interpolation kicks concatenation's butt in 9 of 10 cases. I don't remember if Python has it though. Haven't used it since I discovered Perl 5 years ago. That is for the examples you've been given so far. Usually when concatenation is useful is when you want to add to a string depending on a check, i.e.
    string = "Hello, ";
    string += wordExploded ? "emptiness..." : "World!";
    print string;
    
  • edited February 2011
    Well you've used concatenation (+=) in your example. If the ?: phrasing is what you're referring to as interpolation (I've not heard it called that before), then that's just a nice shortcut for if/then/else.

    For example, you could rewrite your example as:
    string = "Hello, ";
    if wordExploded {
        string += "emptiness...";
    } 
    else {
        string += "World!";
    }
    print string;
    

    Sorry if the code is wrong, it's been ages since I've used Perl. Of course, using ?: makes it much shorter :)

    As far as I know, ?: is NOT available in Python, but it has several other language properties that make up for its omission :)
  • edited February 2011
    Yes, that was an example of where concatenation is useful. ?: is the ternary operator. If I remember correctly, you would to something like
    string = "Hello, " + ["emptiness...", "World!"](!wordExploded)
    
    in Python, since a boolean defaults to 0 for false and 1 for true.

    This is interpolation in Perl:
    my $string = "Hello, $scalar! Here's a comma separated list @list.\n";
    

    Where $scalar is a scalar variable and @list is an array that gets interpolated into the string. You can also set the global $, variable to anything other than commas if you want something else to separate elements in the list on interpolation.

    Of course, you can do all sorts of neat stuff with interpolation, like putting expressions in @{[]} brackets inside the string, but I usually avoid that, since interpolation is a clean way of creating strings, and that usually just clutters it.
  • edited February 2011
    I've never heard that called "interpolation" before, as that has a specific mathematical definition. It's usually called "variable substitution".
  • edited February 2011
    Is it time to sound the Nerd Alert[tm] yet?

    Thanks for the python hint, bamse, it might come in handy :)

    EDIT: Have done some thinking (and more coding, but in C++) today, and think your example would be better rendered with the choices in a tuple, using the [] operator as an index.
    It'd also be valid to use a list with the [] operator, but probably not the () operator.

    That is, the following two are valid:
    string = "Hello, " + ("emptiness...", "World!")[!wordExploded] # tuple version
    string = "Hello, " + ["emptiness...", "World!"][!wordExploded] # list version
    

    but bamse's code isn't quite... :)
  • edited February 2011
    Molokov wrote: »
    but bamse's code isn't quite... :)

    Yeah, I think your tuple variant is what I was thinking of. Like I said, I haven't used python for some years now. Are tuples circular?
  • edited February 2011
    Tuples are pretty similar to lists, except they are immutable (lists are mutable), and thus tuples can be used as keys in dictionaries!

    I think that's the main difference. I don't think they are circular.
Sign in to comment in this discussion.