Linux Ask!

Linux Ask! is a Q & A web site specific for Linux related questions. Questions are collected, answered and audited by experienced Linux users.

Generate a random number in Python

Answer:

It is very easy to generate a random number in Python, see below:

import random

print random.randint(1,100)

The above code print a number between 1 to 100.

Multi-line string in Python

Answer:

In Python, multi-line string are enclosed in triple double (or single) quotes:

E.g.

s = """Line1
Line2
Line3"""

print s

Or

s = '''Line1
Line2
Line3'''

print s

Both methods are valid.

How to modify a single character in a string in Python?

Answer:

Strings in Python are immutable, if you want to modify a single character in a string in Python, you need to do something like the following...

a = list("foo")
a[2] = 'x'
print ''.join(a)

The string "fox " will be printed out.

How to install Easy Install for Python in Ubuntu

Answer:

EasyInstall is a package manager for the Python programming language that provides a standard format for distributing Python programs and libraries (based on the Python Eggs wrapper).

To install the EasyInstall under Ubuntu, type:

# sudo apt-get install python-setuptools python-dev build-essential

Write Python script using utf-8

Answer:

If you have UTF-8 characters in your Python script, you need to declare the following line at the beginning of your script:

# -*- coding: utf-8 -*-