Question

>>>seq = ("a", "b", "c") # This is sequence of strings.
str.join( "-",seq )
SyntaxError: multiple statements found while compiling a single statement

What went wrong here? I tried to change " by ' but it doesn't help...

>>> seq = ("a", "b", "c") 
my_string = "-"
str.join(my_string, seq)
SyntaxError: multiple statements found while compiling a single statement

why?????

Was it helpful?

Solution 2

It can be done even easier, as the object on which is method called is passed as the first argument, so writing

seq = ("a", "b", "c") 
my_string = '-'
print my_string.join(seq)

gives

'a-b-c'

as expected

OTHER TIPS

The problem in your SPECIFIC instance appears to be that you're pasting multiple lines into an interactive interpreter and trying to get them all to parse at once. IDLE (et. al) doesn't like that very much. Do them separately, as in your first example:

>>> seq = ("a","b","c")
>>> str.join("-", seq)
# "a-b-c"

When you did str = "-", str.join(seq) would still work because it's equivalent to my_string.join(seq) as noted above, but using the "long-version" (str.join(separator, sequence)) doesn't work.

If you want to paste a longer line in a Python shell, it's customary to separate by ;, but please don't stick these sorts of lines in Python files. I frequently do this to give people reproducible results via email:

seq = ("a", "b", "c"); my_string = '-'; my_string.join(seq)

An earlier issue was overwriting the str constructor. Start a new shell and try this:

seq = ("a", "b", "c") 
my_string = '-'
str.join(my_string, seq)

you should get this:

'a-b-c'

It is more common to use join as an instance method:

my_string.join(seq)

join is a method of the str data type so you can do...

>>> seq = ("a", "b", "c")
>>> "-".join(seq)
'a-b-c'

Once you have: seq = ("a","b","c")

You can your one of these to syntax (They are actually identical, the latter is more canonical):

>>> str.join("-",seq)
'a-b-c'

>>> "-".join(seq)
'a-b-c'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top