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:
+
), repetition (*
), and membership operators (in
, not in
).\n
for new line and \t
for tabOperator | Description |
+ | 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. |
in | It is known as membership operator. It returns if a particular sub-string is present in the specified string. |
not in | It 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/R | It 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. |
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
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:
Sr. | Escape Sequence | Description | Example |
---|---|---|---|
1. | \newline | It ignores the new line. | print(“Python1 \ Python2 \ Python3”) Output: Python1 Python2 Python3 |
2. | \\ | Backslash | print(“\\”) Output: \ |
3. | \’ | Single Quotes | print(‘\”) Output: ‘ |
4. | \\” | Double Quotes | print(“\””) Output: “ |
5. | \a | ASCII Bell | print(“\a”) |
6. | \b | ASCII Backspace(BS) | print(“Hello \b World”) Output: Hello World |
7. | \f | ASCII Formfeed | print(“Hello \f World!”) Hello World! |
8. | \n | ASCII Linefeed | print(“Hello \n World!”) Output: Hello World! |
9. | \r | ASCII Carriege Return(CR) | print(“Hello \r World!”) Output: World! |
10. | \t | ASCII Horizontal Tab | print(“Hello \t World!”) Output: Hello World! |
11. | \v | ASCII Vertical Tab | print(“Hello \v World!”) Output: Hello World! |
12. | \ooo | Character with octal value | print(“\110\145\154\154\157”) Output: Hello |
13 | \xHH | Character with hex value. | print(“\x48\x65\x6c\x6c\x6f”) Output: Hello |
# 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
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
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.
r
-strings):r
before the string literal.\
) are treated as literal characters, ignoring escape sequences.print(r"C:\\Users\\MILIND BHATT\\Python37")
# Output:
C:\\Users\\MILIND BHATT\\Python37
f
and r
prefixes to create raw f-strings (e.g., rf"some_text{expression}"
).# 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
# 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
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
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.
+
), repetition (*
), and membership operators (in
, not in
).\n
) and tabs (\t
).r
) do not interpret backslashes as escape characters, making them ideal for file paths and regex.%
operator for string formatting, paralleling its functionality with C programming’s printf.All about java servlets Part-2 What is a website? Website is a collection of related…
Let's train the machine. Machine learning is a growing technology which enables computers to learn…
“Unless you try to do something beyond what you have already mastered, you will never…
Whenever you decide to start coding and you want to become budding coder or programmer…
C components are essential elements of a C program, including comments, preprocessor directives, functions, statements,…
All about java servlets Part-2 What is a website? Website is a collection of related…
View Comments
Thanks for thhe marvelous posting! I seriously enjoyed readinng it, you may be a great author.I will
make sure to bookmark your blog and will often come back sometime soon.
I wantt to encourage one to continue your great job, have a nice
holiday weekend! http://boyarka-Inform.com/