combine two strings in python
Asked Answered
B

5

5

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..

Blackbeard answered 15/12, 2019 at 18:25 Comment(0)
S
4

try

y = str(i) + str(x)

it should works.

Smail answered 15/12, 2019 at 18:30 Comment(0)
P
4

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('{}{}'.format(i+x))
Preter answered 15/12, 2019 at 18:28 Comment(1)
maybe is better to use str(n) for integer value before concatenation.Smail
S
4

try

y = str(i) + str(x)

it should works.

Smail answered 15/12, 2019 at 18:30 Comment(0)
G
1

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
Garmaise answered 15/12, 2019 at 18:43 Comment(0)
M
1

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

Meteorology answered 15/12, 2019 at 19:43 Comment(1)
Simple and to the point. Note that you don't really need to use f-strings here; [(item[0]+item[1].split('.')[1], item[2]) for item in list_1] should also work.Maxim
E
0

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]
Effete answered 9/3, 2021 at 10:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.