String
Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes.
Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end.
str = 'hello world'
print(str)
print(str[0])
print(str[0:5])
print(str[6:])
print(str+'test')
print(str+'\ntest')
print(str*3)
print('word' in str)
print('world' in str)
hello world
h
hello
world
hello worldtest
hello world
test
hello worldhello worldhello world
False
True
print("hello {0} how are you {var1}".format("abc",var1=2))
print('a'+"b"+"""c""")
c="""multi
line"""
print(c)
d="second multi \
line"
print(d)
hello abc how are you 2
abc
multi
line
second multi line
v = "hello world"
print(v.capitalize())
print(v.count('o'))
print(v.endswith('ld'))
print(v.find('o'))
print(v.find('oo'))
print(v.index('o'))
#isalpha(),isdigit(),isnumeric(),islower(),isupper(),lower(),upper()
print(len(v))
print(v.strip())
print(v.strip('d'))
print(v.split())
print(v.split("o"))
Hello world
2
True
4
-1
4
11
hello world
hello worl
['hello', 'world']
['hell', ' w', 'rld']
String Functions
- capitalize()
- center(width, fillchar)
- count(str, beg= 0,end=len(string))
- decode(encoding='UTF-8',errors='strict')
- encode(encoding='UTF-8',errors='strict')
- endswith(suffix, beg=0, end=len(string))
- expandtabs(tabsize=8)
- find(str, beg=0 end=len(string))
- index(str, beg=0, end=len(string))
- isalnum()
- isalpha()
- isdigit()
- islower()
- isnumeric()
- isspace()
- istitle()
- isupper()
- join(seq)
- len(string)
- ljust(width[, fillchar])
- lower()
- lstrip()
- maketrans()
- max(str)
- min(str)
- replace(old, new [, max])
- rfind(str, beg=0,end=len(string))
- rindex( str, beg=0, end=len(string))
- rjust(width,[, fillchar])
- rstrip()
- split(str="", num=string.count(str))
- splitlines( num=string.count('\n'))
- startswith(str, beg=0,end=len(string))
- strip([chars])
- swapcase()
- title()
- translate(table, deletechars="")
- upper()
- zfill (width)
- isdecimal()
escape character
Following table is a list of escape or non-printable characters that can be represented with backslash notation. An escape character gets interpreted; in a single quoted as well as double quoted strings.
- \a : Bell or alert
- \b : Backspace
- \e : Escape
- \f : Formfeed
- \n : Newline
- \r : Carriage return
- \s : Space
- \t : Tab
String Special Operators
Assume string variable a holds 'Hello' and variable b holds 'Python', then −
+ : Concatenation - a + b will give HelloPython
* : Repetition - a*2 will give -HelloHello
a[1] : will give e
a[1:4] : will give ell
in : Membership - H in a will give 1
not in : Membership - M not in a will give 1
% : Format - Performs String formatting