Python Forum

Full Version: list of strings to a single string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
How do I convert a list of strings into a single string in a function where the list of strings is my argument? Without using join?
If you have a dictionary with names and some sentences.

This is what I had in mind? 
def somefunction(list_strings):
   #list_strings = dictionary.values()
    for value in list_strings:
        string = list_strings.append()
    return string
Create an empty string before the loop.
Add value to the string on each loop.
Return the string after the loop.
(Nov-01-2016, 05:34 PM)Yoriz Wrote: [ -> ]Create an empty string before the loop.
Add value to the string on each loop.
Return the string after the loop.

Thanks! But how do I import a dictionary from another function into this function? 
And is the empty string just created by this 

string = ''

And is it correct to use append(value) into the empty string?
string_list = ['s', 't', 'r', 'i', 'n', 'g', 's']
string = ''
for item in string_list:
    string += s
print string
>> strings
Use +=, they must be the same type or you will get a TypeError.
(Nov-04-2016, 02:01 AM)kopuz Wrote: [ -> ]
string_list = ['s', 't', 'r', 'i', 'n', 'g', 's']
string = ''
for item in string_list:
    string += s
print string
>> strings
Use +=, they must be the same type or you will get a TypeError.

This will throw an error. The 's' variable is not defined.
(Nov-04-2016, 07:20 AM)wavic Wrote: [ -> ]This will throw an error. The 's' variable is not defined.
And regardless, str.join is the recommended method.
>>> string_list = ['s', 't', 'r', 'i', 'n', 'g', 's']
>>> "".join(string_list)
'strings'
>>>
But the task is to do it without using join()
(Nov-04-2016, 07:41 AM)wavic Wrote: [ -> ]But the task is to do it without using join()

is that to make it a coding challenge or do you have a real-life need where str.join() cannot be used
(Nov-01-2016, 04:58 PM)tebirkes Wrote: [ -> ]How do I convert a list of strings into a single string in a function where the list of strings is my argument? Without using join?

I did not request it
Yeah I missed that in the original post, but the other way is actually bad for more than idiomatic reasons.  Depending on your OS, string concatenation is not guaranteed to be optimized.  It tends to be optimized in Linux versions and not in Windows versions in my experience, but the point is that behavior is not guaranteed in spec.  This means you can write an alg on linux that runs in O(n) and then suddenly encounter users complaining about performance  because they are getting O(n^2).  This is very hard to debug unless you are aware of it.

I hope that this has been addressed in all versions in the current 3x version but I am not aware if it has.
Pages: 1 2