Python is one of the most popular programming languages – it provides an easy-to-read, pseudo-code format of a program. This program makes it easier to understand the overall program structure and algorithm. There are many ways in which particular Python logic can be written. Below are some Python program tricks that will help you to work with strings.
Let’s look at the different operations that can be performed on the string below.
word = 'Sample'print(len(word))
+---+---+---+---+---+---+
| S | a | m | p | l | e |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
Concatenation joins a string with another string.
word = 'Sample'word = word + ' ' + 'trick'print(word)
A string in Python can be indexed to perform operations on the string.
word = 'Sample'print(word[3])word = 'Sample'print(word[-2])word = 'Sample'print(word[::-1])word = 'Sample'for char in reversed(word):print(char)
Slicing allows us to access a substring of characters from a word.
word = 'Sample'print(word[0:3])word = 'Sample'print(word[4:5])word = 'Sample'print(word[:5])
The strip()
method can be used to remove space before and after a string.
print(' Sample '.strip())print('sample'.strip('ple'))
To left fill with ASCII 0
, use the zfill()
method to make a length that is of required string width.
print("10".zfill(6))print("-10".zfill(6))
The find()
method can be used to extract a substring from a string.
print('sample'.find('am',0,5))print('sam' in 'sample')
The isalpha()
method can be used to see if a string contains a number.
print('123'.isalpha())
The isalnum()
method can be used to find if a string is
print(' '.isalnum())print('abc'.isalnum())
The isspace()
method can be used to determine if the string is only a whitespace character.
print(' '.isspace())print('Sample '.isspace())
The lstrip()
method can be used to remove whitespace characters on the left.
print(' sample '.lstrip())