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?
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.
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.
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.
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" .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With