简体   繁体   English

使用python附加字符串

[英]Appending string using python

I need to append to a string. 我需要附加到字符串。 The final string should display like this: 最终的字符串应如下所示:

"""
       One Man
       TWO woman
       FRUITS == "Mango" # "Grapes" # "Banana" 
       VEGE == "Carrot" # "Cabbage" # "Chillie" 

"""

This is the way I am building the fruits string 这就是我建立fruits串的方式

def findFruit(f):
    global fruits
    for ww in f.strip().split():

        if ww.startswith(('Man','Gra','Bana')):
            fruits+= ww

Main (This is where i am constructing the string): 主要(这是我构造字符串的地方):

finalString =     """
           One Man
           TWO woman
           FRUITS == """ + fruits +
           """
           VEGE == "Carrot" # "Cabbage" # "Chillie" 
           """

As you see the string concatenation i have used doesn't resemble the expected output. 如您所见,我使用的字符串连接与预期的输出不同。 How can i solve this? 我该如何解决? I need it to be EXACTLY as the expected output. 我需要它与预期输出完全相同。

Why not just do: 为什么不做:

def findFruit(f):
global fruits
    for ww in f.strip().split():

        if ww.startswith(('Man','Gra','Bana')):
            fruits+= '\"%s\" #' % ww
    fruits = fruits[0:-1]

string.join() could be used for efficient string concatenation: string.join()可用于有效的字符串连接:

def findFruit(f):
    global fruits
    fruits = ' # '.join('"{}"'.format(s) for s in f.strip().split() if s.startswith(('Man', 'Gra', 'Bana')))


>>> fruits
'"Mango" # "Grape" # "Banana"'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM