3. String and Conditional Statements
3. String and Conditional Statements
String:
Indexing:
Slicing:
.format()
Conditional Statements:
Random numbers/strings
String:
We can declare a string in the following ways:
" "
' '
""" """
Concatenation:
"hello" + "world" -> helloworld
Length of String:
len(string) // returns the length of a string
Indexing:
Whenever a string is created, each character gets assigned an index value.
Indexing always starts from 0 .
Syntax: name_of_string[index_value]
string = "Srikanth";
print(string[0]);
Slicing:
Accessing specific part of a string.
Syntax: string[staring_index : ending_index]
string = "Srikanth";
print(string[0:3]);
if no index value is specified then by default is it 0 for starting and length of string for ending
negative indexing is also allowed
.format()
optional method that gives users more control when displaying output.
animal = "cow"
item = "moon"
print("The {} jumped over the {}".format(animal,item))
print("The {0} jumped over the {1}".format(animal,item))
print("The {1} jumped over the {0}".format(animal,item))
animal="Cow"
item="moon"
text = "The {} jumped over the {}"
print(text.format(animal,item))
#PADDING...
animal="Cow"
item="moon"
#formatting number
pi = 3.14159
print("The value of pi is {:.2f}".format(pi))
number = 1000
print("The value of pi is {:,}".format(number))
print("The value of pi is {:b}".format(number)) #binary
print("The value of pi is {:o}".format(number)) #octal
print("The value of pi is {:X}".format(number)) #hexa (lower case x for lower
case output)
Conditional Statements:
SYNTAX: if-elif-else
if(condition):
Statement1
elif(condition):
Statement2
else:
Statement3
if and elif (else if) statements can be used infinite times and elif only comes after if
statement. else statement doesn't require any condition and is always written at the end of
the statements. else is executed if all the if-elif statements are false.
Random numbers/strings
import random
x = random.randint(1,10)
y = random.random() #prints random float values
print(x)
print(round(y,3))
myList=["rock","paper","scissor"]
rps = random.choice(myList)
print(rps)
cards = [1,2,3,4,5,6,7,8,9,"K","J","Q","A"]
random.shuffle(cards)
print(cards)