Strings
adapted from Medium.com
Let us see the different operations that can be performed on the below string.
word = 'Sample'
len(word)
# 6
+---+---+---+---+---+---+
| S | a | m | p | l | e |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
Join a string with another string
word = 'Sample'
word + ' ' + 'trick'
# 'Sample trick'
A string in a python can be indexed to perform operations on the string.
Positive single character
word = 'Sample'
word[3]
# 'p'
Negative single character
word = 'Sample'
word[-2]
# 'l'
String Reverse
word = 'Sample'
word[::-1]
# 'elpmaS'
Reverse string by iterating through string contents.
word = 'Sample'
for char in reversed(word):
print(char)
### Output ###
e
l
p
m
a
S
Slicing allows us to access a substring of characters from a word.
Example 1
word = 'Sample'
word[0:3]
# 'Sam'
Example 2
word = 'Sample'
word[4:5]
# 'le'
Example 3
word = 'Sample'
word[:5]
# 'Sampl'
To remove space before and after a string the strip() method can be used has shown below
' Sample '.strip()
# 'Sample'
'sample'.strip('ple')
# 'sam'
To left fill with ASCII ‘0’’, we can use zfill() method to make a length of required string width.
"10".zfill(6)
# '000010'
"-10".zfill(6)
# '-00010'
The find() method can be used to extract a substring from a string
'sample'.find('am',0,5)
# '1'
'sam' in 'sample'
# True
The isalpha() method can be used to find if a string contains number
'123'.isalpha()
# False
'abc'.isalpha()
# True
'1abc'.isalpha()
# False
The isalnum() method can be used to find if the string contains alphanumeric and at least one character
' '.isalnum()
# False
'abc'.isalnum()
# True
The isspace() method can be used to determine if the string is only whitespace character
' '.isspace()
# True
'Sample '.isspace()
# False
The lstrip() Strings can be used to remove whitespace characters on the left.
' sample '.lstrip()
# 'spacious '
'www.example.com'.lstrip('cmowz.')
# 'example.com'
The rstrip() can be used to remove whitespace characters on the left.
' sample '.rstrip()
# 'spacious '
'mississippi'.rstrip('ipz')
# 'mississ'
The string literals which are prefixed with ‘f’ or ’F’ are called f-string.
word = "Sample"
f"THis is a {word!r} string."
# "THis is a 'Sample' string."
The join() method can be used to join the strings in a list
Test = ["This","is","Sample"]
print(" ".join(Test))
# This is Sample
Same like nos the strings can be multiplied to generate multiple string
word = "Sample"
print(word*3)
# SampleSampleSample
The startswith() and endswith() method can be passed with multiple patterns of substrings to check if it is present.
"sample".startswith(("sam","Sam"))
# True
"sample".endswith(("ple","ple."))
# True
The split() method can be used to split a sentence to multiple words to form a list
"This is a Sample".split()
# ['This', 'is', 'a', 'Sample']
The word which occurs most times in a sentence can be found using the below trick
sentence = "She was young the way an actual young person is young"
split_sentence = sentence.split()
most_frequent_word = max(set(split_sentence),key=split_sentence.count)
# 'young'
The below trick helps in finding, how many times the word is present in the sentence sorted by the increasing rate of word occurence.
from collections import Counter
sentence = "She was young the way an actual young person is young"
split_sentence = sentence.split()
Counter(split_sentence)
# Counter({'young': 3, 'She': 1, 'was': 1, 'the': 1, 'way': 1, 'an': 1, 'actual': 1, 'person': 1, 'is': 1})
The map() method can be used to make all words to capital letters.
sentence = "Quick brown fox".split()
list(map(str.capitalize,sentence))
# ['Quick', 'Brown', 'Fox']
Duplicate words in a sentence can be removed has shown below
sentence = "The sound sounds sound".split()
list(set(sentence))
# ['sound', 'The', 'sounds']
The below trick removes the duplicate word keeping the order of words in the sentence.
from collections import OrderedDict
sentence = "The sound sounds sound".split()
list(OrderedDict.fromkeys(sentence).keys())
# ['The', 'sound', 'sounds']
The reverse() method can be used to reverse a sentence
sentence = "This is Sample".split()
sentence.reverse()
print(sentence)
# ['Sample', 'is', 'This']
The below trick can be used to split a sentence into multiple words and storing in a string variable.
sentence = "This is Sample".split()
first_word, second_word, third_word = sentence
print(first_word)
print(second_word)
print(third_word)
The zip() method can be used to combine two seperate list of strings.
Name = ['Tom', 'Marry', 'Jon']
Age = ['35', '30', '40']
for Name, Age in zip(Name,Age):
print(Name,Age)
### Output ###
Tom 35
Marry 30
Jon 40
The sorted() method can be used to sort the list of strings.
sorted(['string1','string2','string3'],reverse=True)
# ['string3', 'string2', 'string1']