create a string of variable lenght

Peter Otten __peter__ at web.de
Sun Jan 31 07:41:04 EST 2010


Tracubik wrote:

> Hi all,
> 
> i want to print on linux console (terminal) a message like this one:
> 
> ********************************
> error message of variable lenght
> ********************************
> 
> to print the asterisks line i do this:
> 
> def StringOfAsterisks(myString):
>     asterisksString = "*"
>     for i in range(1,len(myString):
>        asterisksString += "*"
>     print asterisksString
> 
> so i create the asterisksString of the lenght i need
> 
> There is a better way of creating asterisksString?

> >>> "*" * 10
'**********'

> the code seem to work for me, but it doesn't work properly if in errorMsg
> there is some "esotic" char like euro char (€):
> 
>>>> euro = "€"
>>>> len(euro)
> 3
> 
> how i can solve this?

This is less likely to fail when you use unicode strings:

>>> def print_message(s):
...     print "*" * len(s)
...     print s
...     print "*" * len(s)
...
>>> print_message(u"You are leaving the € zone")
**************************
You are leaving the € zone
**************************

Peter






More information about the Python-list mailing list