Skip to content

Python Strings – Method and operations

  • by

Python Strings is a Datatype. Strings literals (Any constant value which can be assigned to the variable is called literal/constant)  in python are surrounded by either single quotation marks or double quotation marks.

'Hello World' is the same as "Hello World"

Python Strings Tutorial and Example Functions

Syntax Python Strings

The string can use direct or use a variable like this example.

str1 = "Hello World"
str2 = 'Hello World'

Output: Hello World
Hello World

And Without a variable example

print("Hello World")

Output: Hello World

Python Strings Methods

Here are some of the most common python strings in-build functions :

  • str.lower() : Returns the lowercase version of the string
str1 = "Hello World"

Output: hello world

  • str.upper() : Returns the uppercase version of the string
str1 = "Hello World"


  • str.replace('old', 'new') : returns a string where all occurrences of ‘old’ have been replaced by ‘new’
str1 = "Hello World"
print(str1.replace('Hello', 'Bye'))

Output: Bye World

  • str.strip() : Returns a string with whitespace removed from the start and end
str1 = "  Hello  World   "

Output: Hello World

  • str.startswith('eyehunt') or str.endswith('eyehunt') : Tests if the string starts or ends with the given string
str1 = "Hello World, I am Eyehunt"

Output: False

  • str.find('Hello') : searches for the given string (not a regular expression) and returns the first index where it begins or -1 if not found
str1 = "Hello World, I am Eyehunt"

Output: 6

  • str.split('delim')  : Returns a list of substrings separated by the given delimiter.
str1 = "Hello World, I am Eyehunt"
strSplit = str1.split(",")

Output : [‘Hello World’, ‘ I am Eyehunt’]
Hello World

  • str.len() :  The len() method returns the length of a string.
str1 = "Hello World, I am Eyehunt"

Output: 25

The example of Python string functions – substring, replace, Slicing, splitting, find, formate, join, index and string concatenation follow this tutorial:

Do comment if you have any doubt and suggestion on this tutorial.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6

Python 3.7

All examples are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *