Python

Python Strings & String Methods

A string is a sequence of characters used to store text in Python.

1. Creating a String

A string is created by placing text inside single quotes ' ' or double quotes " ".

Example

x = "Welcome to Python Bootcamp"
print(x)

Output

Welcome to Python Bootcamp

You can also use single quotes:

name = 'Ram'

print(name)

2. Multiline String

Python allows you to create strings that span multiple lines using triple quotes.

You can use either """ """ or ''' '''.

Example

test = """This is the
multiline string in the
Python"""

print(test)

Output

This is the
multiline string in the
Python

A multiline string is useful when you need to store text across multiple lines.

3. Finding the Length of a String

The len() function returns the number of characters in a string.

Syntax

len(string)

Example

x = "Welcome to Python Bootcamp"

print(len(x))

Explanation

len() counts every character in the string, including:

  • Letters
  • Numbers
  • Spaces
  • Special characters

Example

name = "Python"

print(len(name))

Output

6

4. String Indexing

Each character in a string has a position called an index.

Python starts counting indexes from 0.

For example:

Welcome
0123456

The index positions are:

CharacterWelcome
Index0123456

Example

x = "Welcome to Python Bootcamp"

print(x[0])
print(x[20])

The first character is at index 0.

print(x[0])

Output

W

You can access any character by providing its index inside square brackets [].

5. Accessing Characters

Example

x = "Welcome to Python Bootcamp"

print(x[0])
print(x[1])
print(x[2])

Output

W
e
l

You can also access characters from a multiline string.

test = """This is the
multiline string in the
Python"""

print(test[0])

Output

T

6. String Slicing

Slicing is used to extract a portion of a string.

Syntax

string[start:end]

The start index is included, but the end index is not included.

Example

x = "Welcome to Python Bootcamp"

print(x[3:6])

The characters at indexes 3, 4, and 5 are selected.

Output

com

Another example:

print(x[10:20])

7. Leaving Out the End Index

You can leave the end index empty when you want to extract everything from a starting position to the end of the string.

Example

x = "Welcome to Python Bootcamp"

print(x[4:])

This means:

Start from index 4 and continue until the end.

8. Leaving Out the Starting Index

You can also leave the starting index empty.

Example

x = "Welcome to Python Bootcamp"

print(x[:10])

This means:

Start from the beginning and stop before index 10.

Remember that the ending index is not included.

9. Negative Indexing

Python also supports negative indexing.

Negative indexing starts from the end of the string.

For example:

Python
 012345
-6-5-4-3-2-1

The last character has index -1.

Example

x = "Welcome to Python Bootcamp"

print(x[-1])
print(x[-2])

Explanation

  • -1 → last character
  • -2 → second-last character

10. Slicing Using Negative Indexes

You can also use negative indexes while slicing.

Example

x = "Welcome to Python Bootcamp"

print(x[-6:-1])

This extracts characters starting from index -6 up to, but not including, -1.

11. Selecting the Complete String

You can use [:] to select the entire string.

x = "Welcome to Python Bootcamp"

print(x[:])

This returns the complete string.

12. Converting a String to Uppercase

The upper() method converts all alphabetic characters in a string to uppercase.

Example

x = "Welcome to Python Bootcamp"

print(x.upper())

Output

WELCOME TO PYTHON BOOTCAMP

13. Converting a String to Lowercase

The lower() method converts all alphabetic characters to lowercase.

Example

x = "Welcome to Python Bootcamp"

print(x.lower())

Output

welcome to python bootcamp

14. Removing Extra Spaces with strip()

The strip() method removes unnecessary whitespace from the beginning and end of a string.

Example

test = "   welcome you    "

print(test)
print(test.strip())

The first print() displays the spaces as part of the string, while strip() removes the spaces from both ends.

Output

   welcome you    
welcome you

Important

strip() does not remove spaces between words.

For example:

text = "   Hello World   "

print(text.strip())

Output:

Hello World

15. Replacing Text

The replace() method replaces one piece of text with another.

Syntax

string.replace(old, new)

Example

y = "Hello World"

print(y.replace("World", "People"))

Output

Hello People

The original string is not changed automatically. replace() returns a new string.

16. Splitting a String

The split() method divides a string into multiple parts and returns the result as a list.

Splitting by Whitespace

x = "Welcome to Python Bootcamp"

print(x.split())

Output

['Welcome', 'to', 'Python', 'Bootcamp']

By default, split() separates the string using whitespace.

Splitting Using a Specific Character

You can provide a character or text as the separator.

Example

x = "Welcome to Python Bootcamp"

print(x.split("to"))

Output

['Welcome ', ' Python Bootcamp']

The text "to" is used as the separator.

17. String Concatenation

Concatenation means joining two or more strings together.

The + operator is used for string concatenation.

Example

a = "Hello"
b = "World"

c = a + " " + b

print(c)

Output

Hello World

Here:

a + " " + b

joins:

Hello + space + World

18. Combining Strings and Numbers

You cannot directly concatenate a string and an integer using +.

For example:

age = 25

d = "My current age is " + age

This produces a TypeError because age is an integer while the other value is a string.

Instead, Python provides several ways to combine them.

19. Using format()

The format() method allows you to insert values into a string.

Use {} as a placeholder.

Example

age = 25

d = "My current age is {}"

print(d.format(age))

Output

My current age is 25

Here:

{}

is a placeholder.

The value provided to format() replaces the placeholder.

20. Printing String and Number Separately

Another simple approach is to pass multiple values to print().

Example

age = 25

print("My current age is", age)

Output

My current age is 25

Python automatically places a space between the values.

21. Multiple Placeholders

You can use multiple {} placeholders in the same string.

Example

quantity = 5
itemno = 230

a = "I want to buy {} quantity of item no {}"

print(a.format(quantity, itemno))

Output

I want to buy 5 quantity of item no 230

Python fills the placeholders from left to right.

22. Using Placeholder Positions

You can also specify the position of each value.

Example

quantity = 5
itemno = 230

test = "I want to buy {0} quantity of item no {1}"

print(test.format(quantity, itemno))

Here:

  • {0} refers to the first value.
  • {1} refers to the second value.

Output

I want to buy 5 quantity of item no 230

You can even change their order:

test = "Item no {1} has a quantity of {0}"

print(test.format(quantity, itemno))

Output

Item no 230 has a quantity of 5

23. Escape Characters

An escape character allows you to represent special characters inside a string.

Escape sequences begin with a backslash \.

One common escape character is \n.

\n — New Line

\n moves the following text to a new line.

Example

a = 'She typed \n"Hello World"'

print(a)

Output

She typed
"Hello World"

24. Double Quotes Inside a String

Suppose you want to write:

He said "Don't worry about it"

If you use double quotes around the entire string, the inner quotes can cause a problem.

This code is incorrect:

z = "He said "Don't worry about it""

Python will not understand where the string begins and ends.

You can solve this using an escape character.

Correct Example

z = "He said \"Don't worry about it\""

print(z)

Output

He said "Don't worry about it"

The \" tells Python that the double quote is part of the string.

25. Other Common Escape Characters

Escape CharacterMeaning
\nNew line
\tTab
\\Backslash
\'Single quote
\"Double quote

Example

print("Hello\nWorld")
print("Hello\tWorld")
Output
Hello
World
Hello    World

 

 

Interactive Sandbox
Python