How do I convert a number to a string in Python?
Answer:
To convert a number to a string in Python, try the str() function.
foo = str( 999 );
print foo + ' is a string';
Result is :
999 is a string
Linux Ask! is a Q & A web site specific for Linux related questions. Questions are collected, answered and audited by experienced Linux users.
How do I convert a number to a string in Python?
Answer:
To convert a number to a string in Python, try the str() function.
foo = str( 999 );
print foo + ' is a string';
Result is :
999 is a string
How do I find the current module name in Python?
Answer:
The easiest way is to look at the look at the predefined global variable __main__. If it has the value "__main__", it means the program is run as a script (not as imported module).
E.g.
def main():
print 'Running test...'
if __name__ == '__main__':
main()
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.