In this article Escape Characters in Python we give the information about these are used to perform special operations on strings, such as creating a new line, using a tab, or displaying special characters that cannot normally be written directly into the string.
Escape Characters in Python:
Updating Strings in Python
Strings in Python are immutable, which means you cannot directly change any particular character of the string. However, you can use some alternative methods to transform strings, such as creating a new string or adding or changing part of it.
Let’s see how strings can be updated:
- Adding new parts to a string (Concatenation):
You can create a new string by concatenating two or more strings using the + operator.
Example
text = “Hello”
updated_text = text + “, World!” # ‘Hello, World!’
print(updated_text)
Replacing part of a string:
Since you can’t transform strings directly, you have to create a new string by slicing that part of the string.
Example
text = “Hello, World!”
updated_text = text[:7] + “Python!” # ‘Hello, Python!’
print(updated_text)
Here text[:7] gets “Hello,” followed by “Python!” is added.
- Reassigning a String:
You can reassign a string to a variable, storing the new value in the variable.
Example
text = “Good Morning”
text = “Good Evening” #updated the string
print(text) #Output: Good Evening
Using a loop to replace characters:
If you want to replace each character in a string based on some conditions, you can pass the string through a loop and then convert it to a new string.
Example
text = “abcde”
updated_text = “”
for char in text:
if char == ‘a’:
updated_text += ‘A’
else:
updated_text += char
print(updated_text) #OutPut: Abcde
Changing the case of a string (Case Conversion):
You can use built-in functions such as upper(), lower(), and title() to change the case of a string.
Example:
text = “hello world”
updated_text = text.upper() # ‘HELLO WORLD’
print(updated_text)
Replacing Substrings:
You can replace a particular part of a string with another part by using the replace() function.
Example:
text = “I love Java”
updated_text = text.replace(“Java”, “Python”) # ‘I love Python’
print(updated_text)
Conclusion
Strings are immutable in Python, but you can update strings in a variety of ways such as slicing the string, concatenating, and using built-in functions like replace(). It provides you with a flexible and effective way to convert an existing string.
Escape Characters in Python
Escape characters are special symbols that begin with a backslash (\).These are used to perform special operations on strings, such as creating a new line, using a tab, or displaying special characters that cannot normally be written directly into the string.
Common escape characters
Escape sequence | description | example |
\’ | Display single quote (‘) | ‘I\’m a student.’ |
\” | Display double quote (“”). | “She said, \”Hello!\”” |
\\ | display backslash() | print(“This is a backslash: \”) |
\n | Construction of new line | print(“Hello\nWorld!”) |
\t | use tab | print(“Hello\tWorld!”) |
\r | carriage return | print(“Hello\rWorld!”) |
\b | backspace | print(“Hello\bWorld!”) |
\f | form feed | print(“Hello\fWorld!”) |
\v | vertical tab | print(“Hello\vWorld!”) |
\0 | null | print(“Hello\0World!”) |
Examples of Escape Characters
- Single and Double Quotes:
single_quote = ‘I\’m learning Python.’
double_quote = “He said, \”Python is great!\””
print(single_quote) #Outout: I’m learning Python.
print(double_quote) # Outout: He said, “Python is great!”
Construction of new line:
print(“Hello,\nWorld!”)
# Outout:
# Hello,
# World!
Using Tabs:
print(“Hello,\tWorld!”)
# Output: Hello, World! (with tab space)
Use of backslash:
print(“This is a backslash: \”)
# Output: This is a backslash:\
Uses of carriage return:
print(“Hello\rWorld!”)
# Output: World! (Overwrites the word Hello)
Conclusion
Escape characters in Python are used to display special symbols and functions inside strings. Using them correctly can make your code more effective and readable. Knowledge of escape characters gives you greater flexibility and control with strings.
Built-In String Methods
Python has many built-in methods available for working with strings. These methods help in performing various operations on strings, such as converting, checking, and formatting values.
Here are some of the major built-in string methods:
- upper()
Converts all characters in the string to uppercase letters.
Example
text = “hello”
print(text.upper()) # Output: HELLO
- lower()
Converts all characters in the string to lowercase letters.
Example:
text = “HELLO”
print(text.lower()) # Output: hello
- capitalize()
Converts the first character of the string to uppercase and all the rest to lowercase.
Example
text = “hello world”
print(text.capitalize()) # Output: Hello world
4.title()
Converts the first character of each word in the string to uppercase.
Example:
text = “hello world”
print(text.title()) # Output: Hello World
- strip()
Removes a space (or any other character) from the beginning and end of the string.
Example:
text = “Hello World!”
print(text.strip()) # Output: Hello World!
- replace(old, new)
Replaces the old substring in the string with the new substring.
Example:
text = “I like Python.”
print(text.replace(“Python”, “Java”)) # Output: I like Java.
-
find(sub)
Returns the index of the first occurrence of substring sub. If not found, returns -1.
Example:
text = “Hello, World!”
print(text.find(“World”)) # Output: 7
8.count(sub)
Returns the total number of occurrences of substring sub in the string.
Example:
text = “banana”
print(text.count(“a”)) # Output: 3
- split(separator)
Splits the string at the given separator and returns a list as a result.
Example
text = “Hello, World!”
print(text.split(“, “)) # Output: [‘Hello’, ‘World!’]
- join(iterable)
Appends a string to an iterable (such as a list). It is used to concatenate strings.
Example:
words = [‘Hello’, ‘World’]
sentence = ” “.join(words)
print(sentence) #Output: Hello World
- startswith(prefix)
Checks whether the string starts with prefix or not. If yes, returns True, otherwise False.
Example:
text = “Hello, World!”
print(text.startswith(“Hello”)) # Output: True
- endswith(suffix)
Checks whether the string ends with a suffix. If yes, returns True, otherwise False.
Example:
text = “Hello, World!”
print(text.endswith(“!”)) # Output: True
Conclusion
Built-in string methods in Python make the process of working with your strings simple and effective. Using these methods, you can easily modify, inspect, and format strings. It makes your programming work more efficient.
User Input in Python
The input() function is used to receive user input in Python. This function takes data from the console as a string input. Whatever input the user gives, it is always received as a string. If you need to convert to another data type, you will have to do it manually.
using input() function
Syntax:
variable_name = input(“Prompt message: “)
variable_name: The variable in which the input given by the user will be stored.
“Prompt message: “: This is the message that will be shown to the user on the screen.
Example
- Ordinary Use:
variable_name: The variable in which the input given by the user will be stored.
“Prompt message: “: This is the message that will be shown to the user on the screen.
Example
- Ordinary Use:
name = input(“Enter your name: “)
print(“Hello, ” + name + “!”)
Output:
Enter your name: John
Hello, John!
Numeric input: If you want to receive input as a number, you must convert it to int() or float().
age = input(“Enter your age: “)
age = int(age) #convert string to integer
print(“You are ” + str(age) + ” years old.”)
Output:
Enter your age: 25
You are 25 years old.
Multi-word input: When the user inputs more than one word, they are all received together as one string.
hobbies = input(“Enter your hobbies, separated by commas: “)
hobbies_list = hobbies.split(“,”) # Convert string to list
print(“Your hobbies are: ” + “, “.join(hobbies_list))
Output:
Enter your hobbies, separated by commas: reading, painting, swimming
Your hobbies are: reading, painting, swimming
Conclusion
You can easily get data from the user by using input() function in Python. This function provides you with an interface for user input with a custom prompt message.
Note that all inputs come as strings, so if you need a special data type, you’ll have to convert it manually.
Some More:
POP- Introduction to Programming Using ‘C’
OOP – Object Oriented Programming
DBMS – Database Management System
RDBMS – Relational Database Management System
Join Now: Data Warehousing and Data Mining