Main Content

Underlining in Perl and Python - the x and * operator in use

Archive - Originally posted on "The Horse's Mouth" - 2008-04-12 04:59:58 - Graham Ellis

Perl's x operator - yes, that is the letter x - is used to replicate the string on the left the number of times given to the right. "What use is THAT" I have been asked in the past, by delegates feeling that it's a solution looking for a problem. Well - as an example, it's a great way to output just enough "-" characters - or anything else in a fixed with font - to underline a title.


print "Your name? " ;
chop ($name = <STDIN>);
 
print $name,"\n";
print "-" x length($name),"\n";


And here I am testing that ...

Dorothy:qc2 grahamellis$ perl titlit
Your name? Graham
Graham
------
Dorothy:qc2 grahamellis$ perl titlit
Your name? Graham Ellis
Graham Ellis
------------
Dorothy:qc2 grahamellis$


In Python, the * operator on a string object will achieve the same goal:

line = raw_input("your name ")
print line
print "-" * len(line)


And running that ...

Dorothy:qc2 grahamellis$ python pytit
your name Python Trainer
Python Trainer
--------------
Dorothy:qc2 grahamellis$ python pytit
your name Perl Trainer
Perl Trainer
------------
Dorothy:qc2 grahamellis$