Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating objects of different types into a string (Python)

Tags:

python

string

I have been learning Python for two weeks now I created a function which displays your biographical data. I want to know how to put objects of different data types into one string

As you can see, the data includes strings, an int and a boolean. I want to be able to display them as a single string. So far my function only displays them individually like this: ('1000000', 'Bob', 17, False) I want to it display like this: '<1000000,Bob,17,False>'

def student_data(name, age, student_number, enrolled):
    age = int(age)
    true = "true"
    false = "false"
    # check to see if user is enrolled or not.
    if enrolled == true:        
        enrolled = True
    else:        
        enrolled = False
    data = (student_number, name, age, enrolled,) 
    return (data)

data = student_data("Jana", 17, "1001291657", "false")
print (data)
like image 380
Janarthanan Manoharan Avatar asked Aug 18 '26 22:08

Janarthanan Manoharan


1 Answers

The easy answer to the question 'Concatenating objects of different types into a string' is to use map:

>>> list_of_obj=['string', 1234, 123.4, {1:'one'}]
>>> map(str, list_of_obj)
['string', '1234', '123.4', "{1: 'one'}"]

Or a list comprehension:

>>> [str(e) for e in list_of_obj]
['string', '1234', '123.4', "{1: 'one'}"]

In each case, you are applying the built-in function str to each object in a list.

However, may I suggest writing a class to keep track of students:

class Student(object):
    def __init__(self, name, age, number, enrolled=True):
        self.name=name
        self.age=age
        self.number=number
        self.enrolled=enrolled

Then add a method to the class to format it the way you want:

    # Note indentation to be part of the class definition of Student...
    def __str__(self):
        seq=(self.name, self.age, self.number, self.enrolled)
        return '<{}>'.format(', '.join([str(e) for e in seq]))

Then create a student:

>>> student1=Student('Bob Jones', 23, 12345, True)

Then the format is as you define it to be:

>>> print student1   
<Bob Jone, 23, 12345, True>

As stated in the comments, I find it not so Pythonic to redefine true = "true" and false = "false" Just use True and False directly. The main reason, besides not confusing others (or yourself) is that you loose Python's sense of 'truthy' vs 'falsey':

>>> false = "false"
>>> bool(false)
True
like image 177
dawg Avatar answered Aug 20 '26 10:08

dawg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!