Concatenate string with array values - python

I'm using Python and want to be able to create an array and then concatenate the values with a string in a certain format. I'm hoping below will explain what I mean.
name_strings = ['Team 1', 'Team 2']
print "% posted a challenge to %s", %(name_strings)
Where each value from name_strings will be placed in the %s spot. Any help is much appreciated.

One way might be to expand the array in to the str format function...
array_of_strings = ['Team1', 'Team2']
message = '{0} posted a challenge to {1}'
print(message.format(*array_of_strings))
#> Team1 posted a challenge to Team2

You're very close, all you need to do is remove the comma in your example and cast it to a tuple:
print "%s posted a challenge to %s" % tuple(name_strings)
Edit: Oh, and add that missing s in %s as #falsetru pointed out.
Another way of doing it, without casting to tuple, is through use of the format function, like this:
print("{} posted a challenge to {}".format(*name_strings))
In this case, *name_strings is the python syntax for making each element in the list a separate argument to the format function.

Remove ,:
print "% posted a challenge to %s", %(name_strings)
# ^
The format specifier is incomplete. Replace it with %s.
print "% posted a challenge to %s" %(name_strings)
# ^
String formatting operation require a tuple, not a list : convert the list to a tuple.
name_strings = ['Team 1', 'Team 2']
print "%s posted a challenge to %s" % tuple(name_strings)
If you are using Python 3.x, print should be called as function form:
print("%s posted a challenge to %s" % tuple(name_strings))
Alternative using str.format:
name_strings = ['Team 1', 'Team 2']
print("{0[0]} posted a challenge to {0[1]}".format(name_strings))

concatenated_value = ' posted a challenge to '.join(name_strings)

Related

What's the difference between using a variable or %s in Python string formatting?

What is the difference between defining a variable and using it in a string and putting %s in a string and passing in the value after?
site = "Stackoverflow"
site + " is great!"
"%s is great!" % "Stackoverflow"
Printing either of these gives the same result so when is it better to use one over the other?
If you want to keep certain string constants in the same file, or on the top most of the file, you can declare the string with the placeholders as constants, then replace the placeholders with actual variable at run time through the % syntax.
This also allows greater re-usability.
Eg. you can store a single constant "%s is %s years old".
Using this syntax might also make the string more readable.
For two strings, there is little difference.
For multiple strings, s1 + s2 + s3 is less efficient, as it has to create a temporary str object for the first concatenation, where as both "%s %s %s" % (s1, s2, s3) and "{} {} {}".format(s1, s2, s3) creates the final str object immediately.
One:
'string' + 'string'
Two:
'%s %s' % ('one', 'two')
'{} {}'.format('one', 'two')
There is a great article on this here: https://pyformat.info/
Also the docs are a great resource: https://docs.python.org/2/library/string.html#format-string-syntax
Version one is less efficient with larger amounts of concatenation.

Append or Add to string of specific index

I have a list of class objects 'x'. I am trying to create a new list by appending certain attribute values of the objects but I would like to append more that one attribute per index. For example, what I currently get:
x = blah.values()
newList = []
for i in range(len(x)):
if x[i].status == 'ACT':
newList.append(str(x[i].full_name)),
newList.append(str(x[i].team))
else:
pass
print newList
The above code provides me with something like:
['Victor Cruz', 'NYG', 'Marcus Cromartie', 'SF',....]
What I am trying to get:
['Victor Cruz NYG', 'Marcus Cromartie SF',....]
How can I append more than one attribute per index? Hope this make sense, I can try to further elaborate if needed, thanks!
You can use .format() in order to format your string. Notice the space between {} {}
for i in range(len(x)):
if x[i].status == 'ACT':
newList.append("{} {}".format(x[i].full_name,x[i].team) )
Another way is using "%s" % string notation
newList.append("%s %s" % (str(x[i].full_name),str(x[i].team)))
Another example of .format using.
"{} is {}".format('My answer', 'good')
>>> "My answer is good"
You could put the items into one string using .format() and append the string once:
for i in range(len(x)):
if x[i].status == 'ACT':
newList.append('{} {}'.format(x[i].full_name, x[i].team))
On a lighter note, using a list comprehension is a great alternative for creating your list:
newList = ['{} {}'.format(o.full_name, o.team) for o in blah.values() if o.status == 'ACT']
You'll notice that range and len are no longer used in the comprehension, and there is no longer need for indexing.

Formatting of title in Matplotlib

I have the following python code:
def plot_only_rel():
filenames = find_csv_filenames(path)
for name in filenames:
sep_names = name.split('_')
Name = 'Name='+sep_names[0]
Test = 'Test='+sep_names[2]
Date = 'Date='+str(sep_names[5])+' '+str(sep_names[4])+' '+str(sep_names[3])
plt.figure()
plt.plot(atb_mat_2)
plt.title((Name, Test, Date))
However when I print the title on my figure it comes up in the format
(u'Name=X', u'Test=Ground', 'Date = 8 3 2012')
I have the questions:
Why do I get the 'u'? Howdo I get rid of it along with the brackets and quotation marks?
This also happens when I use suptitle.
Thanks for any help.
plt.title receives a string as it's argument, and you passed in a tuple (Name, Test, Date). Since it expects a string it tried to transform it to string using the tuple's __str__ method which gave you got output you got. You probably want to do something like:
plat.title('{0} {1}, {2}'.format(Name, Test, Date))
How about:
plt.title(', '.join(Name,Test,Date))
Since you are supplying the title as an array, it shows the representation of the array (Tuple actually).
The u tells you that it is an unicode string.
You could also use format to specify the format even better:
plt.title('{0}, {1}, {2}'.format(Name, Test, Date))
In Python > 3.6 you may even use f-string for easier formatting:
plt.title(f'{Name}, {Test}, {Date}')
I'd like to add to #Gustave Coste's answer: You can also use lists directly in f-strings
s="Santa_Claus_24_12_2021".split("_")
print(f'Name={s[0]}, Test={s[1]}, Date={s[2]} {s[3]} {s[4]}')
result: Name=Santa, Test=Claus, Date=24 12 2021. Or for your case:
plt.title(f'Name={sep_names[0]}, Test={sep_names[2]}, Date={sep_names[5]} {sep_names[4]} {sep_names[3]}')

List comprehension and simplifying code

I use Python/MySQLdb frequently and often format a list of categories for MySQL. The below code turns a list of categories into 'ADD COLUMN a FLOAT, ADD COLUMN b FLOAT, ADD COLUMN c FLOAT'. I want to figure out how best to simplify this piece of code, allowing for arbitrary change to generic string 's' (e.g. 'ADD COLUMN %s FLOAT' could easily be '%s = %d' or "%s = '%s'"). Is there some form of list comprehension which works?
categories = ['a','b','c']
select_l = []
for cat in categories:
s = 'ADD COLUMN %s FLOAT' % (cat)
select_l.append(s)
select_s = ", ".join(select_l)
I could create a method, but there seems to many examples where it wouldn't handle a specific need. Thanks
Using a generator expression, this can be written as a one-liner:
select_s = ", ".join('ADD COLUMN %s FLOAT' % cat for cat in categories)

Printing named tuples

In Python 2.7.1 I can create a named tuple:
from collections import namedtuple
Test = namedtuple('Test', ['this', 'that'])
I can populate it:
my_test = Test(this=1, that=2)
And I can print it like this:
print(my_test)
Test(this=1, that=2)
but why can't I print it like this?
print("my_test = %r" % my_test)
TypeError: not all arguments converted during string formatting
Edit:
I should have known to look at Printing tuple with string formatting in Python
Since my_test is a tuple, it will look for a % format for each item in the tuple. To get around this wrap it in another tuple where the only element is my_test:
print("my_test = %r" % (my_test,))
Don't forget the comma.
You can do this:
>>> print("my_test = %r" % str(my_test))
my_test = 'Test(this=1, that=2)'
It's unpacking it as 2 arguments. Compare with:
print("dummy1 = %s, dummy2 = %s" % ("one","two"))
In your case, try putting it in a tuple.
print("my_test = %r" % (my_test,))
The earlier answers are valid but here's an option if you don't care to print the name. It's a one-liner devised to pretty print only the contents of a named tuple of arbitrary length. Given a named tuple assigned to "named_tuple" the below yields a comma-delineated string of key=value pairs:
', '.join(['{0}={1}'.format(k, getattr(named_tuple, k)) for k in named_tuple._fields])
As now documented at 4.7.2. printf-style String Formatting, the % string formatting or interpolation operator is problematic:
The [printf-style string formatting operations] exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals or the str.format() interface helps avoid these errors
So for example you can now do:
from collections import namedtuple
Test = namedtuple('Test', ['this', 'that'])
my_test = Test(this=1, that=2)
print("my_test = {0!r}".format(my_test))

Categories