Python String Functions with Examples

Strings are everywhere! While interacting with the user, i.e., while getting input or displaying output, you’ll use strings more than any other data structure.

In this article, you’ll learn what Python strings are and how you can manipulate and use them in your Python program with Python String Functions.

Strings in Python

A single character or a sequence of characters identify as strings in Python. Strings are one of the primitive data structures in Python.

A very important thing while working with strings is that strings are “immutable”. That is, once we create a string, we cannot change its value.

So to manipulate strings, we’ll need to create new strings as we go, while the original strings stay intact.

How to Spot Python String?

We always enclose a string within quotes, either single-quotes or double-quotes. There can be as many characters in a string as you want, given there’s enough memory.

For Example

>>> "This is a string"

Output

‘This is a string’
>>> 'This is a string'

Output

‘This is a string’

Python also allows empty string in Python.

>>> ''

Output

>>> ""

Output

We can assign a string to a variable using the assignment operator.

>>> x = "Techvidvan"
>>> print(x)

Output

Techvidvan

Python String Indexing

Recall that a string is just a sequence of characters. And like any other sequence in Python, strings support indexing too. That is, we can access individual characters of a string using a numeric index.

Python starts counting from zero when it comes to numbering index locations of a sequence. So the first character of a string is at index 0, the second character at index 1 and so on. We also have negative indices which count from right to left, starting with -1.

Indexing uses square bracket notation. So this is how we access a character at index ind of a string my_string:

my_string[ind]

For Example

>>> say = "Hi from Techvidvan!"
>>> say[0]
'H'
>>> say[3]
'f'
>>> say[5]
'o'
>>> say[-1]
'!'
>>> say[-3]
'a'
>>> say[-5]
'd'
>>> 

Python String Slicing

We can extend the square bracket notation to access a substring(slice) of a string. We can specify start, stop and step(optional) within the square brackets as:

my_string[start:stop:step]
  • start: It is the index from where the slice starts. The default value is 0.
  • stop: It is the index at which the slice stops. The character at this index is not included in the slice. The default value is the length of the string.
  • step: It specifies the number of jumps to take while going from start to stop. It takes the default value of 1.

For Example

>>> say = "Hi from Techvidvan!"
>>> say[3:6]
'fro'
>>> say[:10]
'Hi from Te'
>>> say[4:]
'rom Techvidvan!'
>>> say[1:11:3]
'ir c'
>>> say[::2]
'H rmTcvda!'
>>> say[::-1]
'!navdivhceT morf iH'
>>> 

Python String Operations

1. Python + operator – String Concatenation operator

The + operator joins all the operand strings and returns a concatenated string.

For Example

>>> x = "This is "
>>> y = "Python"
>>> z = x + y + '.'
>>> print(z)

Output

This is Python.

2. Python * operator – String Replication operator

The * operator takes two operands – a string and an integer. It then returns a new string which is a number of repetitions of the input string. The integer operand specifies the number of repetitions.

For Example

>>> x = 3 * "Hi!"
>>> print(x)

Output

Hi!Hi!Hi!
>>> y = "Go!" * 3
>>> print(y)

Output

Go!Go!Go!

String Methods in Python

Everything in Python is an object. A string is an object too. Python provides us with various methods to call on the string object.

Let’s look at each one of them.

Note that none of these methods alters the actual string. They instead return a copy of the string.This copy is the manipulated version of the string.

1. s.capitalize() in Python

Capitalizes a string

>>> s = "heLLo BuDdY"
>>> s2 = s.capitalize()
>>> print(s2)

Output

Hello buddy

2. s.lower() in Python

Converts all alphabetic characters to lowercase

>>> s = "heLLo BuDdY"
>>> s2 = s.lower()
>>> print(s2)

Output

hello buddy

3. s.upper() in Python

Converts all alphabetic characters to uppercase

>>> s = "heLLo BuDdY"
>>> s2 = s.upper()
>>> print(s2)

Output

HELLO BUDDY

4. s.title() in Python

Converts the first letter of each word to uppercase and remaining letters to lowercase

>>> s = "heLLo BuDdY"
>>> s2 = s.title()
>>> print(s2)

Output

Hello Buddy

5. s.swapcase() in Python

Swaps case of all alphabetic characters.

>>> s = "heLLo BuDdY"
>>> s2 = s.swapcase()
>>> print(s2)

Output

‘HEllO bUdDy’

6. s.count(<sub>[, <start>[, <end>]])

Returns the number of time <sub> occurs in s.

For Example

>>> s = 'Dread Thread Spread'
>>> s.count('e')
3
>>> s.count('rea')
3
>>> s.count('e', 4, 18)
2
>>>

7. s.find(<sub>[, <start>[, <end>]])

Returns the index of the first occurrence of <sub> in s. Returns -1 if the substring is not present in the string.

For Example

>>> s = 'Dread Thread Spread'
>>> s.find('Thr')
6
>>> s.find('rea')
1
>>> s.find('rea', 4, 18)
8
>>> s.find('x')
-1
>>> 

8. s.isalnum() in Python

Returns True if all characters of the string are alphanumeric, i.e., letters or numbers.

For Example

>>> s = "Tech50"
>>> s.isalnum()
True
>>> s = "Tech"
>>> s.isalnum()
True
>>> s = "678"
>>> s.isalnum()
True

9. Python s.isalpha()

Returns True if all the characters in the string are alphabets.

For Example

>>> s = "Techvidvan"
>>> s2 = "Tech50"
>>> s.isalpha()
True
>>> s2.isalpha()
False
>>> 

10. Python s.isdigit()

Returns True if all the characters in the string are numbers.

For Example

>>> s1 = "Tech50"
>>> s2 = "56748"
>>> s1.isdigit()
False
>>> s2.isdigit()
True
>>>

11. s.islower()

Returns True if all the alphabets in the string are lowercase.

For Example

>>> s1 = "Tech"
>>> s2 = "tech"
>>> s1.islower()
False
>>> s2.islower()
True
>>>

12. s.isupper()

Returns True if all the alphabets in the string are uppercase.

For Example

>>> s1 = "Tech"
>>> s2 = "TECH"
>>> s1.isupper()
False
>>> s2.isupper()
True

13. s.lstrip([<chars>])

Removes leading characters from a string. Removes leading whitespaces if you don’t provide a <chars> argument.

14. s.rstrip([<chars>])

Removes trailing characters from a string. Removes trailing whitespaces if you don’t provide a <chars> argument.

15. s.strip([<chars>])

Removes leading and trailing characters from a string. Removes leading and trailing whitespaces if you don’t provide a <chars> argument.

Example of lstrip(), rstrip() and strip():

>>> s = "   Techvidvan   "
>>> s.lstrip()
'Techvidvan   '
>>> s.rstrip()
'   Techvidvan'
>>> s.strip()
'Techvidvan'
>>> 

16. s.join(<iterable>)

Joins elements of an iterable into a single string. Here, s is the separator string.

Example

>>> s1 = ' '.join(['We', 'are', 'Coders'])
>>> print(s1)
We are Coders
>>> s2 = ':'.join(['We', 'are', 'Coders'])
>>> print(s2)
We:are:Coders
>>> 

17. s.split(sep = None, maxspit = -1)

Splits a string into a list of substrings based on sep. If you don’t pass a value to sep, it splits based on whitespaces.

Example

>>> l = 'we are      coders'.split()
>>> l
['we', 'are', 'coders']
>>> l = 'we are      coders'.split('e')
>>> l
['w', ' ar', '      cod', 'rs']

Summary

In this article, we learned what Python strings are. We also learned how to spot a string in Python program.

Then we saw the ways to access an individual character or a slice of characters from a string. We learned the different operations we can perform on strings in Python.

Lastly, we saw how to manipulate strings using built-in methods.

TechVidvan Team

The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today’s tech industry.