Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

python - How to combine two strings from a list of character signs

I would like to combine 'test1' and 'test2' into 1 string with all possible character signs which are listed in sent_Str. It worked, but not the way i actually want it to be. I want the character signs to be between 'test1' and 'test2' so its more obvious that it's a combine word.

here is my code.

sentence = ['test1']
sentence1 = ['test2']
sent_str = [ '', '-', '*', '=' ]
lst = []
for i in sentence:
    sent_str[+0] += str(i)
    sent_str[+1] += str(i)
    sent_str[+2] += str(i)
    sent_str[+3] += str(i)
for i in sentence1:
    sent_str[+0] += str(i)
    sent_str[+1] += str(i)
    sent_str[+2] += str(i)
    sent_str[+3] += str(i)
sent_str1 = sent_str
lst.append(sent_str1)
print(sent_str1)

the output is like below:

['test1test2', '-test1test2', '*test1test2', '=test1test2']

but i want it to be like this

['test1test2', 'test1-test2', 'test1*test2', 'test1=test2']

anyone who could help?

question from:https://stackoverflow.com/questions/65845777/how-to-combine-two-strings-from-a-list-of-character-signs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
sentence = ['test1']
sentence1 = ['test2']
sent_str = [ '', '-', '*', '=' ]

res = [j + i + k for i in sent_str for j in sentence for k in sentence1]

print(res) # ['test1test2', 'test1-test2', 'test1*test2', 'test1=test2']

You can use a list comprehension with three loops.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...