Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining every 2 string to 1 string

Tags:

python

list

I have a list a

list = ['247400015203223811', 'DPF', '247400015203223813', 'ZPF']

I want to get a list of strings like ["247400015203223811, DPF", "247400015203223813, ZPF"] combining every 2 strings to 1 string

I tried like

list2 = []
list = ['247400015203223811', 'DPF', '247400015203223813', 'ZPF']

        for i in range(0, len(list), 2):
            list2.append(list[i] + list[i])

is this even possible?

like image 562
Chaban33 Avatar asked Sep 12 '18 15:09

Chaban33


People also ask

How do I combine all strings into one string?

You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.

How do I combine multiple strings into one?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

How do I combine double strings?

The “+” operator with a String acts as a concatenation operator. Whenever you add a String value to a double using the “+” operator, both values are concatenated resulting a String object. In-fact adding a double value to String is the easiest way to convert a double value to Strings.

Can you merge on strings?

You can merge/concatenate/combine two Java String fields using the + operator, as shown in this example code: // define two strings String firstName = "Fred"; String lastName = "Flinstone"; // concatenate the strings String fullName = firstName + lastName; The String fullName now contains "FredFlinstone" .


1 Answers

import itertools

def grouper(iterable, n, fillvalue=None):
    """ Collect data into fixed-length chunks or blocks.

        grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    """
    args = [iter(iterable)] * n
    return itertools.zip_longest(*args, fillvalue=fillvalue)

x = ["a", "b", "c", "d", "e"]
x_grouped = [", ".join(pair) for pair in grouper(x, 2, "")]

print(x_grouped)  # -> ['a, b', 'c, d', 'e, ']

You can use the grouper function from an itertools recipe. If you have an odd number of strings in your list, you can specify a fillvalue.

like image 198
Victor Avatar answered Sep 21 '22 15:09

Victor