Open In App

Interesting facts about strings in Python | Set 2 (Slicing)

Last Updated : 04 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Creating a String

Strings in Python can be created using single quotes or double quotes or even triple quotes.

# Python Program for
# Creation of String

# Creating a String
# with single Quotes
String1 = ‘Welcome to the Geeks World’
print(“String with the use of Single Quotes: “)
print(String1)

# Creating a String
# with double Quotes
String1 = “I’m a Geek”
print(“\nString with the use of Double Quotes: “)
print(String1)

# Creating a String
# with triple Quotes
String1 = ”’I’m a Geek and I live in a world of “Geeks””’
print(“\nString with the use of Triple Quotes: “)
print(String1)

# Creating String with triple
# Quotes allows multiple lines
String1 = ”’Geeks
For
Life”’
print(“\nCreating a multiline String: “)
print(String1)

Output:
String with the use of Single Quotes:
Welcome to the Geeks World

String with the use of Double Quotes:
I’m a Geek

String with the use of Triple Quotes:
I’m a Geek and I live in a world of “Geeks”

Creating a multiline String:
Geeks
For
Life

Accessing characters in Python
In Python, individual characters of a String can be accessed by using the method of Indexing. Indexing allows negative address references to access characters from the back of the String, e.g. -1 refers to the last character, -2 refers to the second last character, and so on.
While accessing an index out of the range will cause an IndexError. Only Integers are allowed to be passed as an index, float or other types that will cause a TypeError.

# Python Program to Access
# characters of String

String1 = “GeeksForGeeks”
print(“Initial String: “)
print(String1)

# Printing First character
print(“\nFirst character of String is: “)
print(String1[0])

# Printing Last character
print(“\nLast character of String is: “)
print(String1[-1])

Output:
Initial String:
GeeksForGeeks

First character of String is:
G

Last character of String is:
s

String Slicing

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.

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:




# A python program to illustrate slicing in strings 
  
x = "Geeks at work"
  
# Prints 3rd character beginning from 0 
print (x[2]) 
  
# Prints 7th character 
print (x[6]) 
  
# Prints 3rd character from the rear beginning from -1 
print (x[-3]) 
  
# Length of string is 10 so it is out of bound 
print (x[15]) 


Output:

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

 

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

string_name[beginning: end : step]
  • 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:




# A python program to illustrate 
# print substrings of a string 
x = "Welcome to GeeksforGeeks"
  
# 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])       


Output:

lco
oet
Ge

How to print single quote or double quote on screen?
We can do that in the following two ways:

  • First one is to use escape character to display the additional quote.
  • The second way is by using mix quote, i.e., when we want to print single quote then using double quotes as delimiters and vice-versa.

Example-




print("Hi Mr Geek.")
  
# use of escape sequence
print("He said, \"Welcome to GeeksforGeeks\"")    
  
print('Hey so happy to be here')
  
# use of mix quotes
print ('Getting Geeky, "Loving it"')                


Output:

Hi Mr Geek.
He said, "Welcome to GeeksforGeeks"
Hey so happy to be here
Getting Geeky, "Loving it"

How to print escape character instead?

If there is a requirement of printing the escape character(\) instead,then if user mention it in a string interpreter will think of it as escape character and will not print it.In order to print the escape character user have to use escape character before ‘\’ as shown in the example.




# Print Escape character
print (" \\ is back slash ")


Output:

 \ is back slash


Similar Reads

Py-Facts - 10 interesting facts about Python
Python is one of the most popular programming languages nowadays on account of its code readability and simplicity. All thanks to Guido Van Rossum, its creator. I've compiled a list of 10 interesting Facts in the Python Language. Here they are:1. There is actually a poem written by Tim Peters named as THE ZEN OF PYTHON which can be read by just wri
4 min read
Interesting facts about strings in Python | Set 1
1. Strings are Immutable Once a string is defined, it cannot be changed. # Python3 program to show that # string cannot be changed a = 'Geeks' # output is displayed print(a) a[2] = 'E' print(a) # causes error Output: Traceback (most recent call last): File "/home/adda662df52071c1e472261a1249d4a1.py", line 9, in a[2] = 'E' TypeError: 'str' object do
4 min read
Interesting facts about data-types and modifiers in C/C++
Here are some logical and interesting facts about data-types and the modifiers associated with data-types:- 1. If no data type is given to a variable, the compiler automatically converts it to int data type. C/C++ Code #include &lt;iostream&gt; using namespace std; int main() { signed a; signed b; // size of a and b is equal to the size of int cout
4 min read
Interesting Facts about C++
C++ is a general-purpose, object-oriented programming language. It supports generic programming and low-level memory manipulation. Bjarne Stroustrup (Bell Labs) in 1979, introduced the C-With-Classes, and in 1983 with the C++. Here are some awesome facts about C++ that may interest you: The name of C++ signifies the evolutionary nature of the chang
2 min read
Interesting Facts about Linux
Linux is community-developed and open source operating system for computers, servers, mainframes, embedded devices, and mobile devices. It is supported on nearly every major computer platforms including SPARC, ARM and, x86 building it as one of the most extensively supported operating systems. Here are some facts about Linux that may interest you:
2 min read
Interesting Facts about C#
C# is a general-purpose, modern and object-oriented programming language pronounced as "C Sharp" or "C Hash". It was developed by Microsoft led by Anders Hejlsberg and his team within the .NET initiative and was approved by the European Computer Manufacturers Association (ECMA) and International Standards Organization (ISO). C# is among the languag
3 min read
Interesting Facts About Java
Java: A general-purpose, high-level programming language. It is developed by Sun Microsystems. It was developed by a mini team of engineers which is known as the Green Team. They initiated this language in 1991. Here are some interesting facts about Java: The initial name of java was "Oak". It was changed to Java by Sun's marketing department chang
2 min read
Interesting Facts about PYGAME
Pygame is a set of python module which is used in designing video games. In Pygame, there are computer graphics and sound libraries in order to develop high quality and user interactive games. Pygame was developed by Pete Shinners. Till 2000, it was a community project, later on it was released under open source free software General Public License
2 min read
Interesting Facts about Macros and Preprocessors in C
In a C program, all lines that start with # are processed by preprocessor which is a special program invoked by the compiler. by this we mean to say that the ‘#’ symbol is used to process the functionality prior than other statements in the program, that is, which means it processes some code before run-time or say during the compile-time. In a ver
6 min read
Interesting facts about Increment and Decrement operators in Java
Increment operator is used to increment a value by 1. There are two varieties of increment operator: Post-Increment: Value is first used for computing the result and then incremented.Pre-Increment: Value is incremented first and then the result is computed. Example Java Code //INCREMENTAL OPERATOR //Let's see what exactly happens when we use these
5 min read
Practice Tags :