Creating String in Python
Strings indexing and splitting
str[1]
str[0:]
str[1:5]
str[2:4]
str[:3]
str[4:7]
format method
str = "HELLO"
print(str[1])
str = "JAVATPOINT"
# Start Oth index to end
print(str[0:])
# Starts 1th index to 4th index
print(str[1:5])
# Starts 2nd index to 3rd index
print(str[2:4])
# Starts 0th to 2nd index
print(str[:3])
#Starts 4th to 6th index
print(str[4:7])
output
JAVATPOINT
AVAT
VA
JAV
TPO
str = 'JAVATPOINT'
print(str[-1])
print(str[-3])
print(str[-2:])
print(str[-4:-1])
print(str[-7:-2])
Reversing the given string
print(str[::-1])
print(str[-12])
Consider the following example:
Python string is the collection of the characters surrounded by single quotes, double quotes, or triple quotes. The computer does not understand the characters; internally, it stores manipulated character as the combination of the 0's and 1's.
str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
It returns the IndexError because 6th index doesn't exist
print(str[6])
Output:
H
E
L
L
O
IndexError: string index out of range
Consider the following example to understand the real use of Python operators.
str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
print('w' in str) # prints false as w is not present in str
print('wo' not in str1) # prints false as wo is present in str1.
print(r'C://python37') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello
Output:
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello
The format() method
The format() method is the most flexible and useful method in formatting strings. The curly braces {} are used as the placeholder in the string and replaced by the format() method argument. Let's have a look at the given an example:
Using Curly braces
print("{} and {} both are the best friend".format("Devansh","Abhishek"))
*Positional Argument *
print("{1} and {0} best players ".format("Virat","Rohit"))
Keyword Argument
print("{a},{b},{c}".format(a = "James", b = "Peter", c = "Ricky"))
Output:
Devansh and Abhishek both are the best friend
Rohit and Virat best players
James,Peter,Ricky
Top comments (0)