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"
Hello something else
Env: Python 2.7.18
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)10
[1, 2]
{'k2': 'v2', 'k1': 'v1'}
Env: Python 2.7.18
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
Hello 10 Hello 10
Env: Python 2.7.18
Concatenate two strings using +
Strings can be concatenated using + operator.
s1 = "Hello" s2 = "World" s3 = "." s = s1 + s2 + s3 print s
HelloWorld.
Env: Python 2.7.18