## 2.3.7 Is there an equivalent to Perl’s chomp() for removing trailing newlines from strings? 

You can use$_{S.rstrip("\r
")}$ to remove all occurrences of any line terminator from the end of the string$_{S}$ without removing other trailing whitespace. If the string$_{S}$ represents more than one line, with several empty lines at the end, the line terminators for all the blank lines will be removed: 

>>> lines =("line 1 \r
 " ... " \r
 " ... " \r
 ") >>> lines.rstrip(" 
\r ") 'line 1 ' 

Since this is typically only desired when reading text one line at a time, using S.rstrip() this way works well. 

## 2.3.8 Is there a scanf() or sscanf() equivalent? 

Not as such. 

For simple input parsing, the easiest approach is usually to split the line into whitespace-delimited words using the split() method of string objects and then convert decimal strings to numeric values using int() or float() . split() supports an optional “sep” parameter which is useful if the line uses something other than whitespace as a separator. 

For more complicated input parsing, regular expressions are more powerful than C’s$_{sscanf()}$ and better suited for the task. 

## 2.3.9 What does ‘UnicodeDecodeError’ or ‘UnicodeEncodeError’ error mean? 

See the unicode-howto. 

## 2.4 Performance 

## 2.4.1 My program is too slow. How do I speed it up? 

That’s a tough one, in general. First, here are a list of things to remember before diving further: 

• Performance characteristics vary across Python implementations. This FAQ focuses on CPython . 

• Behaviour can vary across operating systems, especially when talking about I/O or multi-threading. 

• You should always find the hot spots in your program before attempting to optimize any code (see the$_{profile}$ module). 

• Writing benchmark scripts will allow you to iterate quickly when searching for improvements (see the$_{timeit}$ module). 

• It is highly recommended to have good code coverage (through unit testing or any other technique) before potentially introducing regressions hidden in sophisticated optimizations. 

That being said, there are many tricks to speed up Python code. Here are some general principles which go a long way towards reaching acceptable performance levels: 

• Making your algorithms faster (or changing to faster ones) can yield much larger benefits than trying to sprinkle micro-optimization tricks all over your code. 

• Use the right data structures. Study documentation for the bltin-types and the$_{collections}$ module. 

