Remove special symbols / punctuation from a string
Given:
str1 = "/*Jon is @developer & musician"
Expected Output:
"Jon is developer musician"
Solution 1: Use string functions translate() and maketrans().
The string.punctuation constant contain all special symbols.
import string
str1 = "/*Jon is @developer & musician"
print("Original string is ", str1)
new_str = str1.translate(str.maketrans('', '', string.punctuation))
print("New string is ", new_str)
Solution 2: Using regex replace pattern in a string
import re
str1 = "/*Jon is @developer & musician"
print("Original string is ", str1)
# replace special symbols with ''
res = re.sub(r'[^\w\s]', '', str1)
print("New string is ", res)
Removal all characters from a string except integers
Given:
str1 = 'I am 25 years and 10 months old'
Expected Output:
2510
str1 = 'I am 25 years and 10 months old'
print("Original string is", str1)
# Retain Numbers in String
# Using list comprehension + join() + isdigit()
res = "".join([item for item in str1 if item.isdigit()])
print(res)
Write a program to find words with both alphabets and numbers from an input string.
Given:
str1 = "Emma25 is Data scientist50 and AI Expert"
Expected Output:
Emma25
scientist50
str1 = "Emma25 is Data scientist50 and AI Expert"
print("The original string is : " + str1)
res = []
# split string on whitespace
temp = str1.split()
Given:
str1 = "/*Jon is @developer & musician"
Expected Output:
"Jon is developer musician"
Solution 1: Use string functions translate() and maketrans().
The string.punctuation constant contain all special symbols.
import string
str1 = "/*Jon is @developer & musician"
print("Original string is ", str1)
new_str = str1.translate(str.maketrans('', '', string.punctuation))
print("New string is ", new_str)
Solution 2: Using regex replace pattern in a string
import re
str1 = "/*Jon is @developer & musician"
print("Original string is ", str1)
# replace special symbols with ''
res = re.sub(r'[^\w\s]', '', str1)
print("New string is ", res)
Removal all characters from a string except integers
Given:
str1 = 'I am 25 years and 10 months old'
Expected Output:
2510
str1 = 'I am 25 years and 10 months old'
print("Original string is", str1)
# Retain Numbers in String
# Using list comprehension + join() + isdigit()
res = "".join([item for item in str1 if item.isdigit()])
print(res)
Write a program to find words with both alphabets and numbers from an input string.
Given:
str1 = "Emma25 is Data scientist50 and AI Expert"
Expected Output:
Emma25
scientist50
str1 = "Emma25 is Data scientist50 and AI Expert"
print("The original string is : " + str1)
res = []
# split string on whitespace
temp = str1.split()