Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
community creator

How to perform functions related to Python String

Saikrishna Reddy Nimma

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.

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

1. Concatenation

Concatenation joins a string with another string.

word = 'Sample'
word = word + ' ' + 'trick'
print(word)

2. Indexed Access of Strings

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)

3. Slicing of Strings

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])

4. Remove leading and trailing characters

The strip() method can be used to remove space before and after a string.


print('   Sample   '.strip())

print('sample'.strip('ple'))

5. Left fill with ASCII ‘0’

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))

6. Find Substring

The find() method can be used to extract a substring from a string.

print('sample'.find('am',0,5))

print('sam' in 'sample')

7. Find if the string contains numbers

The isalpha() method can be used to see if a string contains a number.

print('123'.isalpha())

8. Find if the string is alphanumeric

The isalnum() method can be used to find if a string is alphanumericcontains at least one character.

print(' '.isalnum())

print('abc'.isalnum())

9. Find if the string is having only whitespace

The isspace() method can be used to determine if the string is only a whitespace character.

print(' '.isspace())
print('Sample  '.isspace())

10. Remove Spaces on the left side of the string

The lstrip() method can be used to remove whitespace characters on the left.

print('   sample   '.lstrip())

RELATED TAGS

python
community creator

CONTRIBUTOR

Saikrishna Reddy Nimma
RELATED COURSES

View all Courses

Keep Exploring