[Tutor] working with strings in python3

Alan Gauld alan.gauld at btinternet.com
Wed Apr 20 00:00:44 CEST 2011


"Rance Hall" <ranceh at gmail.com> wrote

> String formatting doesn't work for me in this case
> as the message is sort of dynamic.

I don;t understand that, string formatting is probably
the most dynamic way of constructing strings
there is, its designed for dynamic data! If your data
is really dynamic the only two ways that make sense
are joining lists or using format strings. The latter
combines dynamic with output control too.

> Way too much logic around printing a statement.

I don;t see how format strings can be a problem
combined with complex logic, string contatenation
would be much more complex to deal with.

> A list might make sense, but printing a message
> one word at a time ...

The list doesn't need to contaain single words - unless
that is really how dynamic your output is - but even
then it will be faster than string concatenation - more
typically the list will contain sentence fragments

You can even use indirection for more dynamic use cases:


# assume gender and hour are dynamically input
# or calculated elsewhere
stringList = ["Good", "Morning", "Afternoon","Evening", 
"Night","Sir","Madam"]

fields = []
if 6 < hour < 12:  fields.append(1)
elif 12 <= hours < 18: fields.append(2)
elif 18 <= hours <=23 fields.append(3)
else: fields.append(4)

if gender == "Male": fields.append(5)
else: fields.append(6)

print( " ".join([stringList[n] for n in fields]) )

> But are CLI apps so rare that this sort of thing just doesn't happen
> anymore?  This seems like such a basic thing and deprecating it 
> seems
> rather harsh.

They aren't rare and concatenation isn't deprecated,
but there are other alternatives that may be more
suitable depending on your usage.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list