List to string
Steven D'Aprano
steve at REMOVE.THIS.cybersource.com.au
Sun Mar 18 01:19:39 EDT 2007
On Sat, 17 Mar 2007 21:28:56 -0700, Hitesh wrote:
>
> Hi,
>
> I've a list like this..
> str1 = ['this is a test string inside list']
That's a bad name for the variable. It's called "str1" but it is a list.
> I am doing it this way.
>
> for s in str1:
> temp_s = s
> print temp_s
That's redundant. Why not just "print s"? That will work perfectly.
You can do any of the following, depending on what you are trying to do.
my_list = ["first string", "second string", "third string"]
# print the entire list as a string
print my_list
# print each string individually
for s in my_list:
print s
# save the string representation of the entire list as a variable
my_str = repr(my_list)
another_str = str(my_list)
Note that repr() and str() may have different results, depending on the
type of object you pass into them.
# extract the first string into another variable
my_str = my_list[0]
# insert the third string into another string
my_string = "This is the %s here." % my_list[2]
Hope that helps.
--
Steven.
More information about the Python-list
mailing list