Easy Learning, Python Strings QAs for Beginner’s to Pro Part-2

Table of Contents
< All Topics
Print

Easy Learning, Python Strings QAs for Beginner’s to Pro Part-2

Learning Python basics through questions is a fantastic way to grasp the fundamentals of Python programming. This article delves into String Basics, explaining that Python strings are collections of characters enclosed in single, double, or triple quotes. We’ll explore indexing and slicing, where string indexing begins at 0, and reverse indexing starts from -1. Remember, Python strings are immutable, but you can create new strings by reassigning variables. Internally, characters are stored as binary streams, encoded using ASCII or Unicode. Furthermore, we’ll discuss:

  • Python Strings: The page explains the basics of Python strings, including indexing, slicing, and immutability.
  • String Operators: It covers various string operators like concatenation (+), repetition (*), and membership operators (in,not in).
  • Escape Sequences: Detailed descriptions and examples of escape sequences in Python, such as\nfor new line and\tfor tab
OperatorDescription
+It is known as concatenation operator used to join the strings given either side of the operator.
*It is known as repetition operator. It concatenates the multiple copies of the same string.
[]It is known as slice operator. It is used to access the sub-strings of a particular string.
[:]It is known as range slice operator. It is used to access the characters from the specified range.
inIt is known as membership operator. It returns if a particular sub-string is present in the specified string.
not inIt is also a membership operator and does the exact reverse of in. It returns true if a particular substring is not present in the specified string.
r/RIt is used to specify the raw string. Raw strings are used in the cases where we need to print the actual meaning of escape characters such as “C://python”. To define any string as a raw string, the character r or R is followed by the string.
%It is used to perform string formatting. It makes use of the format specifiers used in C programming like %d or %f to map their values in python. We will discuss how formatting is done in python.

Examples of above operators

str = "Hello"     
str1 = " world"    

print(str*3) # prints HelloHelloHello    

# + is known as concatenation operator used to join the strings given either side of the operator.

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

Can you help me to define Escape Sequence in python.

Escape sequences in Python are special character combinations that represent non-printable characters or characters that have a special meaning in strings. They start with a backslash () followed by a specific character. Here is a brief description of it:

In a more precise way:

  • The backslash can be followed by a special character and it interpreted differently.
  • The single quotes inside the string must be escaped. We can apply the same as in the double quotes.

The allowable list of an escape sequence in Python

Examples

# using triple quotes  
print('''They said, "What's there?"''')  
# Output

They said, "What's there?"
# escaping double quotes  
print("They said, \"What's going on?\"")  
# Output

They said, "What's going on?"
# escaping single quotes  
print('They said, "What\'s going on?"')  
# Output

They said, "What's going on?"
# use of \newline escape sequence:  It ignores the new line.

print("Python1 \ Python2 \ Python3") 
# Output: 
Python1 Python2 Python3
# use of \n : Moves cursor to next line

print("Python1 \n Python2 \n Python3") 
# Output: 
Python1 
Python2 
Python3
# Use of \b  :  ASCII Backspace(BS)

print("Hello \b World") 
# Output: 

Hello World
#Use of \ooo   : Character with octal value


print("\110\145\154\154\157") 
# Output: 

Hello
# Use of \xHH  :  Character with hex value.

print("\x48\x65\x6c\x6c\x6f") 
# Output: 

Hello

One more simple example

print("C:\\Users\\Milind Bhatt\\Python32\\Lib")  
print("This is the \n multiline quotes")  
print("This is \x48\x45\x58 representation")  
# Output:

C:\Users\Milind Bhatt\Python32\Lib
This is the 
 multiline quotes
This is HEX representation

What is difference between Raw String and Formatted Strings in Python?

In python you can make strings either via raw manner for string preparation or via format() functionIn the raw manner, strings can be created by placing the text within single or double quotes. This method is useful for simple strings that do not require any special formatting. On the other hand, the format() function allows for more dynamic string creation by inserting variables or expressions within the string. This can be particularly useful when generating output that depends on user input or changing data. Ultimately, both methods have their own use cases and can be leveraged depending on the specific requirements of the string being created.

1. Raw Strings (Prefixed withr-strings):

  • A raw string is denoted by adding anrbefore the string literal.
  • In raw strings, backslashes (\) are treated as literal characters,ignoring escape sequences.
  • Useful for specifying file paths on Windows or writing regular expressions
  • For example:
print(r"C:\\Users\\MILIND BHATT\\Python37")  
# Output:

C:\\Users\\MILIND BHATT\\Python37

2. Formatted Strings (f-strings):

  • Introduced in Python 3.6, f-strings allow you to embed expressions inside string literals.
  • Combine thefandrprefixes to create raw f-strings (e.g.,rf"some_text{expression}").
  • For Examples:
# Example-1

print(f"C:\\Users\\MILIND BHATT\\Python37")  
# Output:

C:\Users\MILIND BHATT\Python37
# Example-2

person1= "Ajay"
person2= "Vijay
print(f"Do you know {person1} and {person2} both are the best friend")
# Output:

Do you know Ajay and Vijay both are the best friend

3. Formatted Strings using format() function):

  • 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
  • Examples:
# Using Curly braces  
print("{} and {} both are the best friend".format("Ajay","Vijay"))  
# Output:
Ajay and Vijay both are the best friend
#Positional Argument  
print("Now a days {1} and {0} best are players of Indian Cricket  ".format("Virat","Rohit"))  
#output:
Now a days Rohit and Virat best are players of Indian Cricket  
#Keyword Argument
print("{a}, {b}, {c}".format(a = "Apple", b = "Banana", c = "Pineapple"))  
#Output:
Apple, Banana, Pineapple

3. Python String Formatting Using % Operator

  • Python allows us to use the format specifiers used in C’s printf statement.
  • The format specifiers in Python are treated in the same way as they are treated in C.
  • However, Python provides an additional operator %, which is used as an interface between the format specifiers and their values.
  • In other words, we can say that it binds the format specifiers to the values.

Example:

Integer = 10   
Float = 1.290    
String = "Milind"    
print(" Hi I am Integer ... My value is %d \n Hi I am float ... My value is %f \n Hi I am string ... My value is %s"%(Integer,Float,String))   
# Output:

 Hi I am Integer ... My value is 10 
 Hi I am float ... My value is 1.290000 
 Hi I am string ... My value is Milind

Conclusion

This document provides a comprehensive overview of Python string fundamentals, highlighting essential concepts such as string immutability, indexing, and slicing. It introduces key string operators and escape sequences, explaining their usage with clear examples. The article also distinguishes between raw strings and formatted strings, detailing the methods of string creation and manipulation in Python.

Key Take Aways

  • Python strings are collections of characters that can be enclosed in single, double, or triple quotes and are immutable.
  • Indexing in Python starts from 0, and reverse indexing starts from -1, allowing for various techniques to access string characters.
  • The article explains string operators, including concatenation (+), repetition (*), and membership operators (in,not in).
  • Escape sequences in Python provide ways to represent special characters, such as new lines (\n) and tabs (\t).
  • Raw strings (prefixed withr) do not interpret backslashes as escape characters, making them ideal for file paths and regex.
  • Formatted strings (f-strings) introduced in Python 3.6 allow embedding expressions within string literals for dynamic content creation.
  • The document discusses the use of the%operator for string formatting, paralleling its functionality with C programming’s printf.

Recommended Readings

Leave a comment