Python String handling codes
Python String handling codes
"
astring = "Hello world!" print("The characters with odd index are '%s'"
%s[1::2]) #(0-based indexing)
print(astring[3:7])
print("The last five characters are '%s'" % s[-
astring = "Hello world!" 5:]) # 5th-from-last to end
print(astring[3:7:2]) # Convert everything to uppercase
Escape Sequence
# escaping double quotes
If we want to print a text like -He
said, "What's there?"- we can print("He said, \"What's there?\"")
neither use single quote or
>>> print("C:\\Python32\\Lib")
double quotes. This will result
into SyntaxError as the text itself C:\Python32\Lib
contains both single and double >>> print("This is printed\nin
quotes. two lines")This is printedin
two lines
>>> print("He said, "What's
there?"") >>> print("This is \x48\x45\
x58 representation")This is
... HEX representation
SyntaxError: invalid syntax
Raw String to ignore
>>> print('He said, "What's
there?"')
escape sequence
Sometimes we may wish to
...
ignore the escape sequences
SyntaxError: invalid syntax inside a string. To do this we can
place r or R in front of the string.
This will imply that it is a raw
string and any escape sequence
An escape sequence starts with a inside it will be ignored.
Common Python
String Methods Boolean operators
rev_str = reversed(my_str)
if len(first_array) + len(second_array)
== 5:
# check if the string is equal to its reverse
print("4")
if list(my_str) == list(rev_str):
print("It is palindrome")
if first_array and first_array[0] == 1: else:
print("5") print("It is not palindrome")
if not second_number:
print("6")
Loops
There are two types of loops in Python,
for and while.
The "for" loop
For loops iterate over a given sequence.
Here is an example:
count=0
while(count<5):
print(count)
count +=1
else:
print("count value reached %d" %
(count))