How to concatenate strings with iteration in a loop?

Peter Otten __peter__ at web.de
Sun Jun 2 03:03:12 EDT 2019


DL Neil wrote:

> On 21/05/19 8:40 PM, Paul Moore wrote:
>> On Tue, 21 May 2019 at 09:25, Frank Millman <frank at chagford.com> wrote:
>>>
>>> On 2019-05-21 9:42 AM, Madhavan Bomidi wrote:
>>>> Hi,
>>>>
>>>> I need to create an array as below:
>>>>
>>>> tempStr =
>>>> year+','+mon+','+day+','+str("{:6.4f}".format(UTCHrs[k]))+','+ \
>>>> 
str("{:9.7f}".format(AExt[k,0]))+','+str({:9.7f}".format(AExt[k,1]))+','+
>>>> \
>>>> 
str("{:9.7f}".format(AExt[k,2]))+','+str("{:9.7f}".format(AExt[k,3]))+','+
>>>> \
>>>> 
str("{:9.7f}".format(AExt[k,4]))+','+str("{:9.7f}".format(AExt[k,5]))+','+
>>>> \
>>>> 
str("{:9.7f}".format(AExt[k,6]))+','+str("{:9.7f}".format(AExt[k,7]))+','+
>>>> \ str("{:9.7f}".format(AExt[k,8]))+','+str("{:9.7f}".format(AExt[k,9]))
>>>>
>>>>
>>>> k is a row index
>>>>
>>>> Can some one suggest me how I can iterate the column index along with
>>>> row index to concatenate the string as per the above format?
>>>>
>>>> Thanks in advance
>>>>
>>>
>>> The following (untested) assumes that you are using a reasonably
>>> up-to-date Python that has the 'f' format operator.
>>>
>>> tempStr = f'{year},{mon},{day},{UTCHrs[k]:6.4f}'
>>> for col in range(10):
>>>       tempStr += f',{AExt[k, col]:9.7f}'
>>>
>> 
>> As a minor performance note (not really important with only 10 items,
>> but better to get into good habits from the start):
>> 
>> temp = [f'{year},{mon},{day},{UTCHrs[k]:6.4f}']
>> for col in range(10):
>>       temp.append(f',{AExt[k, col]:9.7f}')
>> 
>> tempStr = ''.join(tempStr)
>> 
>> Repeated concatenation of immutable strings (which is what Python has)
>> is O(N**2) in the number of chunks added because of the need to
>> repeatedly copy the string.
> 
> 
> A more pythonic approach might be to eschew the "k is a row index" and
> resultant range(), by gathering the temperature readings into a
> list/tuple (tuple unpacking at read-step or zip(), as appropriate). The
> point of which (hah!) is to get rid of "pointers", and replace the
> 'algebra' with more readable code.
> 
> The collection can then be processed into the string using .append()
> and/or .join(), perhaps with a list comprehension/generator...

One way:

temp_str = ",".join(
    itertools.chain(
        (year, mon, day, f"{UTCHrs[k]:6.4f}"),
        (f"{x:9.7f}" for x in AExt[k])
    )
)

This assumes that the magic number 10 is actually len(AExt[k]).




More information about the Python-list mailing list