p

python tutorial - String Python | Interesting facts about strings in Python | Slicing - learn python - python programming



 interesting-facts-about-strings-in-python

Learn Python - Python tutorial - interesting-facts-about-strings-in-python - Python examples - Python programs

Like other programming languages, it’s possible to access individual characters of a string by using array-like indexing syntax. In this we can access each and every element of string through their index number and the indexing starts from 0. Python does index out of bound checking.

what is slicing

So, we can obtain the required character using syntax, string_name[index_position]:

  • The positive index_position denotes the element from the starting(0) and the negative index shows the index from the end(-1).

Example-

python - Sample - python code :

# A python program to illustrate slicing in strings
 
x = "Wiki at work"
 
# Prints 3rd character beginning from 0
print x[2]  
 
# Prints 7th character
print x[6]  
 
# Prints 3rd character from rear beginning from -1
print x[-3] 
 
# Length of string is 10 so it is out of bound
print x[15] 
click below button to copy the code. By Python tutorial team

python tutorial - Output :

Traceback (most recent call last):
  File "8a33ebbf716678c881331d75e0b85fe6.py", line 15, in 
    print x[15] 
IndexError: string index out of range

python - Sample - python code :

e
a
o
click below button to copy the code. By Python tutorial team

Slicing

To extract substring from the whole string then then we use the syntax like

slicing

python - Sample - python code :

string_name[beginning: end : step]
click below button to copy the code. By Python tutorial team
slicing

  • beginning represents the starting index of string
  • end denotes the end index of string which is not inclusive 
  • steps denotes the distance between the two words.

Note: We can also slice the string using beginning and only and steps are optional.

Example-

python - Sample - python code :

# A python program to illustrate
# print substrings of a string
x = "Welcome to Wikitechy"
 
# Prints substring from 2nd to 5th character
print x[2:5]      
 
# Prints substring stepping up 2nd character 
# from 4th to 10th character
print x[4:10:2]    
 
# Prints 3rd character from rear from 3 to 5
print x[-5:-3]
click below button to copy the code. By Python tutorial team

python tutorial - Output :

lco
oet
et

Wikitechy tutorial site provides you all the learn python , python course for beginners , learn python online interactive , how to learn python coding , best online python training , python online course certification free , python training for beginners , online python course free , learn python online free course

Related Searches to Interesting facts about strings in Python | Slicing