简体   繁体   中英

combine two strings in python

I have a list1 like this,

list1 = [('my', '1.2.3', 2),('name', '9.8.7', 3)]

I want to get a new list2 like this (joining first element with second element's second entry);

list2 = [('my2', 2),('name8', 3)]

As a first step, I am checking to join the first two elements in the tuple as follow,

for i,j,k in list1:
    #print(i,j,k)
    x = j.split('.')[1]
    y = str(i).join(x)
    print(y)

but I get this

2
8

I was expecting this;

my2
name8

what I am doing wrong? Is there any good way to do this? a simple way..

The str(i).join(x) , means that you see x as an iterable of strings (a string is an iterable of strings), and you are going to construct a string by adding i in between the elements of x .

You probably want to print('{}{}'.format(i+x)) however:

for i,j,k in list1:
    x = j.split('.')[1]
    print()

try

y = str(i) + str(x)

it should works.

Try this:

for x in list1:
   print(x[0] + x[1][2])

or

for x in list1: 
   print(x[0] + x[1].split('.')[1]) 

output

# my2
# name8

You should be able to achieve this via f strings and list comprehension, though it'll be pretty rigid.

list_1 = [('my', '1.2.3', 2),('name', '9.8.7', 3)]

# for item in list_1
# create tuple of (item[0], item[1].split('.')[1], item[2])
# append to a new list
list_2 = [(f"{item[0]}{item[1].split('.')[1]}", f"{item[2]}") for item in list_1]

print(list_2)

List comprehensions (and dict comprehensions) are some of my favorite things about python3

https://www.pythonforbeginners.com/basics/list-comprehensions-in-python
https://www.digitalocean.com/community/tutorials/understanding-list-comprehensions-in-python-3

Going with the author's theme,

list1 = [('my', '1.2.3', 2),('name', '9.8.7', 3)]

for i,j,k in list1:
    extracted = j.split(".") 
    y = i+extracted[1] # specified the index here instead 
    print(y) 
my2
name8

[Program finished]

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