Jak połączyć elementy listy z pojedynczym ciągiem znaków?

Czy istnieje prostszy sposób łączenia elementów łańcuchowych z listy w pojedynczy łańcuch? Czy mogę użyć funkcji str.join()?

Np. to jest wejście ['this','is','a','sentence'] a to jest pożądane Wyjście this-is-a-sentence

sentence = ['this','is','a','sentence']
sent_str = ""
for i in sentence:
    sent_str += str(i) + "-"
sent_str = sent_str[:-1]
print sent_str
Author: Gino Mempin, 2012-09-17

12 answers

Użycie join:

>>> sentence = ['this', 'is', 'a', 'sentence']
>>> '-'.join(sentence)
'this-is-a-sentence'
>>> ' '.join(sentence)
'this is a sentence'
 1285
Author: Burhan Khalid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-07 20:52:05

Bardziej ogólnym sposobem konwersji list Pythona na ciągi znaków jest:

>>> my_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> my_lst_str = ''.join(map(str, my_lst))
>>> print(my_lst_str)
'12345678910'
 155
Author: Aaron S,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-19 05:56:29

Jest to bardzo przydatne dla początkujących, aby wiedzieć Dlaczego join jest metodą łańcuchową .

Na początku jest to bardzo dziwne, ale potem bardzo przydatne.

Wynikiem join jest zawsze łańcuch znaków, ale obiekt do połączenia może być wielu typów (Generatory, lista, krotki, itp.).

.join jest szybszy, ponieważ przydziela pamięć tylko raz. Lepsze niż klasyczna konkatenacja (zobacz, rozszerzone Wyjaśnienie ).

Kiedy się go nauczysz, jest bardzo wygodny i możesz zrób takie sztuczki, aby dodać nawiasy.
>>> ",".join("12345").join(("(",")"))
Out:
'(1,2,3,4,5)'

>>> list = ["(",")"]
>>> ",".join("12345").join(list)
Out:
'(1,2,3,4,5)'
 48
Author: Wallebot,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-02-05 21:52:42

Edit from the future: Please don ' t use this, ta funkcja została usunięta w Pythonie 3 i Python 2 jest martwy. Nawet jeśli nadal używasz Pythona 2, powinieneś napisać gotowy kod Pythona 3, aby ułatwić nieuniknioną aktualizację.

Chociaż @Burhan Khalid ' s answer jest dobra, myślę, że jest bardziej zrozumiała w ten sposób:

from str import join

sentence = ['this','is','a','sentence']

join(sentence, "-") 

Drugi argument join() jest opcjonalny i domyślnie ma wartość"".

 16
Author: SilentVoid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-12-12 18:06:14

Możemy określić, w jaki sposób mamy połączyć łańcuch. Zamiast " - "możemy użyć ""

sentence = ['this','is','a','sentence']
s=(" ".join(sentence))
print(s)
 3
Author: Abhishek V,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-10-18 07:46:18

Możemy również użyć funkcji reduce:

from functools import reduce

sentence = ['this','is','a','sentence']
out_str = str(reduce(lambda x,y: x+"-"+y, sentence))
print(out_str)
 3
Author: Nishkarsh Dixit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-02-23 15:49:50
list = ['aaa', 'bbb', 'ccc']

string = ''.join(list)
print(string)
>>> aaabbbccc

string = ','.join(list)
print(string)
>>> aaa,bbb,ccc

string = '-'.join(list)
print(string)
>>> aaa-bbb-ccc

string = '\n'.join(list)
print(string)
>>> aaa
>>> bbb
>>> ccc
 3
Author: mounirboulwafa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-09-03 09:18:52

To na pewno pomoże -

arr=['a','b','h','i']     # let this be the list
s=""                      # creating a empty string
for i in arr:
   s+=i                   # to form string without using any function
print(s) 


       
 1
Author: Abhishek Chauhan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-08-07 07:14:54

Jeśli masz mieszaną listę treści. I chce to podciągnąć. Oto jeden sposób:

Rozważ tę listę:

>>> aa
[None, 10, 'hello']

Konwertuj go na string:

>>> st = ', '.join(map(str, map(lambda x: f'"{x}"' if isinstance(x, str) else x, aa)))
>>> st = '[' + st + ']'
>>> st
'[None, 10, "hello"]'

Jeśli jest to wymagane, Konwertuj z powrotem na Listę:

>>> ast.literal_eval(st)
[None, 10, 'hello']
 1
Author: wiredcontrol,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-27 10:21:57

Jeśli chcesz wygenerować ciąg znaków oddzielonych przecinkami w wyniku końcowym, możesz użyć czegoś takiego:

sentence = ['this','is','a','sentence']
sentences_strings = "'" + "','".join(sentence) + "'"
print (sentences_strings) # you will get "'this','is','a','sentence'"
Mam nadzieję, że to komuś pomoże.
 0
Author: CarMoreno,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-07-02 20:02:19

Bez .metoda join () możesz użyć tej metody:

my_list=["this","is","a","sentence"]

concenated_string=""
for string in range(len(my_list)):
    if string == len(my_list)-1:
        concenated_string+=my_list[string]
    else:
        concenated_string+=f'{my_list[string]}-'
print([concenated_string])
    >>> ['this-is-a-sentence']

Tak więc, w tym przykładzie, gdy python dotrze do ostatniego słowa z listy, nie powinien dodawać " - " do concenated_string. Jeśli nie jest to ostatnie słowo Twojego łańcucha zawsze dołącza łańcuch " - " do zmiennej concenated_string.

 0
Author: Abdulmecid Pamuk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-07-07 11:03:36
def eggs(someParameter):
    del spam[3]
    someParameter.insert(3, ' and cats.')


spam = ['apples', 'bananas', 'tofu', 'cats']
eggs(spam)
spam =(','.join(spam))
print(spam)
 -2
Author: Pyte,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-05-07 21:46:58