简体   繁体   中英

How To Combine Multiple Strings Contained in 1 variable into 1 String

Im taking a really complex way to do this and am really confused but here I go!

Ok so I basically took the result like a normal dict which is result = j_result['result'] j_result is the variable containing all of the information in the following image.

and then with that im skipping title and simply extracting everything inside the result with this script

def extract_values(obj, key):
            arr = []
            def extract(obj, arr, key):
                if isinstance(obj, dict):
                    for k, v in obj.items():
                        if isinstance(v, (dict, list)):
                            extract(v, arr, key)
                        elif k == key:
                            arr.append(v)
                elif isinstance(obj, list):
                    for item in obj:
                        extract(item, arr, key)
                return arr

            results = extract(obj, arr, key)
            return results
        def listToString(s):

And with that value im replacing all of the weird characters such as [, ], ', etc. when I finally have a good string that parsed everything im left with the pretty string, but the majority of them contain a character | seperating the japanese and english names, I used this script to remove everything before that leaving english

o_string = oe_string.replace(",", "\n")  
for l in o_string.split('\n'):
   thingy1 = l.split('|')[-1] + "\n"
   print(repr(thingy1))

But when I do this it print multiple strings represented through thingy1

example: output coming from the print function in the above script

'string 1'
'string 2'
'string 3'

I want to combine all of the of these strings into 1 string, and seperate new lines with \n.

So in gist instead of having 3 lines I want something that looks like this:

string 1\nstring 2\nstring 3\n

and so on...

Sorry if this isnt the right way to phraze this etc, or for this purpose. But im really at a lost and anything helps.

https://media.discordapp.net/attachments/696842088431485069/701708282162708480/unknown.png?width=720&height=42

So you have a list of strings and want to combine them into a single string with a separator ( \n ) in between them?

That's what .join is for!

l = ['string 1', 'string 2', 'string 3']
joined = '\n'.join(l)
# now joined is 'string 1\nstring 2\nstring 3'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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