Python string quick start tutorial

Python built-in data type string is very frequently used in any python program. Here are some examples of using strings to get started with.

Print a string

s = "Hello"
print s ## with automatic newline after string
print "something else"
Env: Python 2.7.6

Convert int to string

str() convertor can be used to convert int to string or any other type to string.

x = 10
print str(x)
a = [1,2]
print str(a)
d = {"k1":"v1", "k2":"v2"}
print str(d)
[1, 2]
{'k2': 'v2', 'k1': 'v1'}
Env: Python 2.7.6

Print using formatting operator %

Strings can be printed (or assigned) using formatting operator %. It is very convenient way to print multiple values.

s = "Hello"
x = 10
s1 = "%s %s" % (s, x)
print "%s %s" % (s, x)
print s1
Env: Python 2.7.6

Concatenate two strings using +

Strings can be concatenated using + operator.

s1 = "Hello"
s2 = "World"
s3 = "."
s = s1 + s2 + s3
print s
Env: Python 2.7.6

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments