Python: Function that takes a list and a separator and returns a string

python split string by character
python concatenate list of strings
python append to string in loop
python list to string
python string split
list comprehension || python
python concatenate strings
convert list of characters to string python

I need to create a function that takes a list and a separator value as parameters and returns the string representation of the list which is separated by the separator value.

The only built-in functions I can use are range() and str() without any slice expressions, list methods or string methods.

I have put together some code but I know it isn't right as it is displaying a space at the beginning and the separator at the end (separator needs to be only between values).

How can I fix this?

def my_string(my_list, sep=', '):
    string = " "

    for words in my_list:
        string += words + ', '     

    return string

my_list = ["item1", "item2", "item3", "item4"]
list_string = my_string(my_list, sep=', ')
print (list_string)

join() function in Python, The join() method is a string method and returns a string in which the elements of Parameters: The join() method takes iterable – objects capable of returning its Python | Pandas str.join() to join string/list elements with passed delimiter  The Python split string function is one of the String methods. Python split string function is useful to split the given string and return a list of words. This Python split string function accepts two arguments (optional). If you specify the separator to split, then it uses the specified separator to return a list of words.

Keep it simple, join everything except the last word, then add the last word at the end:

# Calculates the length of a list
def my_len(my_list):
    length = 0

    for _ in my_list:
        length += 1

    return length

def my_string(my_list, sep=', '):
    string = ""
    length = my_len(my_list)

    # Loop through indices except last
    for i in range(length - 1):
        string += my_list[i] + sep

    # Add last item on
    string += my_list[i+1]

    return string

my_list = ["item1", "item2", "item3", "item4"]
list_string = my_string(my_list, sep=', ')
print (list_string)
# item1, item2, item3, item4

Note: Since it seems from your requirements you can't use len(), you need to make your own custom function my_len() to do this.

Even though this works, in the real world you want to use sep.join(my_list).

Splitting, Concatenating, and Joining Strings in Python – Real Python, Splitting Without Parameters; Specifying Separators; Limiting Splits With Maxsplit Concatenating With the + Operator; Going From a List to a String in Python With .join() Take the Quiz: Test your knowledge with our interactive “Splitting, of Python 3, like working with data types, dictionaries, lists, and Python functions. How To Convert Python String to List. If we want to convert string to list operation, then we need to use the Python string split() method. Python split() method is used to split the strings and store them in the list. The split() method returns a list of the words in the string, using the “delimiter” as the delimiter string.

def my_string(my_list, separator=", "):
    string = ""
    disp_separator = False
    for i in my_list:
        string += separator if disp_separator else "" # don't display the separator the first time
        string += str(i)
        disp_separator = True
    return string

input : my_string(["item1", "item2", "item3", "item4"]) output : 'item1, item2, item3, item4'

input : my_string([1, 2, 3, 4], separator=' | ') output : '1 | 2 | 3 | 4'

Work with any type who can be convert with str() builtin

Python 3 Notes: Split and Join, .split() splits mary on whitespce, and the returned result is a list of words in mary. This list The method can also be called on the empty string '' as the separator. Python: Function that takes a list and a separator and returns a string - Stack Overflow. I need to create a function that takes a list and a separator value as parameters and returns the string representation of the list which is separated by the separator value. The only built-in fun Stack Overflow. Products. Customers.

Its simple you can use 'join' which is inbuilt function in python.

def my_string(my_list, sep=', '):
    return sep.join(my_list)

my_list = ["item1", "item2", "item3", "item4"]
list_string = my_string(my_list, sep=', ')
print (list_string)

3. Strings, lists, and tuples, Strings, lists, and tuples are all sequence types, so called because they behave Invoking the method causes an action to take place using the value on which the We say that the upper() method returns the string 'Apple' when it is invoked on The string value on which the join method is invoked acts as a separator that  Python string startswith() function returns True if the string starts with the given prefix, otherwise it returns False. endswith() Python string endswith() function returns True if the string ends with the given suffix, otherwise it returns False.

How to Convert Python List to String with Examples, Python provides a magical join() method that takes a sequence and converts it to a Desc: Function to convert List of strings to a string with a separator """ def all the strings in list final_str = seperator.join(input_seq) return final_str # List of  Python String: Exercise-8 with Solution. Write a Python function that takes a list of words and returns the length of the longest one. Sample Solution:-

Python String join() method, The join() string method returns a string by joining all the elements of an iterable, of an iterable (such as list, string and tuple) by a string separator (the string on The join() method takes an iterable (objects capable of returning its members  The split () function is a function when applied to any string it returns the list of strings after recognizing the delimiter and breaks the string into substrings. This method is used to split the strings into characters. Sometimes it is required to split large strings into small chunks of characters or substring.

Python String split() Method, Python String split() Method. ❮ String Split a string into a list where each word is a list item: a list. You can specify the separator, default separator is any whitespace. setting the maxsplit parameter to 1, will return a list with 2 elements! Another trick for achieving the conversion of the list to string is using the map function with join. The map function takes a function and applies it to iterable that can be a list, tuple etc. The map function returns a list of the result after applying that function to the iterable.

  • FWIW, for the record, the actual real world every day solution to this would be return sep.join(my_list)
  • You should use sep if your passing it into the function.
  • @deceze you are right, however OP explicitly stated that it is not allowed to use function from string.
  • Can you use len()?
  • @Max I know. I was just stating this for future visitors.
  • enumerate is a built in method. OP can't use any built in except range and str
  • Brilliant idea to implement your own len method! However I believe some_list[some_index] would count as a list method? Not 100% on that
  • @The That's why questions with such arbitrary restrictions are… less than helpful really.
  • @TheLazyScripter Thats true. I assumed that the OP would be allowed to index lists. A list method IMO is list.append(), list.extend() etc. Indexing is part of the language constructs for Python, and many other languages.
  • @RoadRunner Yeah, but some_list[some_index] is just a nice way to say some_list.__getitem__(some_index).
  • @MaxPowers Good point. But that gets called under the hood from Python? The Python interpreter takes some_list[some_index] and calls some_list.__getitem__(some_index) instead. I'm not sure if that counts. That would just be silly if indexing is restricted from the OP.
  • This produces an TypeError on the 6th line and does not return anything.
  • sorry, i write my_list insead of i, i fixed that
  • OP said he can't use any string methods. I.E .join