Python Strings Tutorial: Learn Strings Manipulation with Codes and Examples

Article by: Manish Methani

Last Updated: October 6, 2021 at 2:04pm IST
2 min 47 sec read

Strings

Strings are used to represent text data in Python. In Python, a string is represented by str class. We can create a string by enclosing text data in single quotes (') or double quotes (").

Here's an example:

# Example of string
x = 'Hello, World!'
y = "This is a string."
print(x)
print(y)

Output:

Hello, World!
This is a string.

String Operations

We can perform various operations on strings in Python. Here are some common string operations:

  • Concatenation: We can concatenate two or more strings using the + operator.
  • Repetition: We can repeat a string a certain number of times using the * operator.
  • Indexing: We can access a specific character in a string using its index.
  • Slicing: We can extract a part of a string using slicing.
  • Length: We can find the length of a string using the len() function.
  • Upper/Lower Case: We can convert a string to upper or lower case using the upper() and lower() methods.

Here are some examples:

# Example of string operations
x = 'Hello,'
y = ' World!'
z = x + y
print(z)

a = 'Hello,'
b = a * 3
print(b)

c = 'Python'
print(c[0])  # access first character
print(c[1:4])  # slice from index 1 to 4
print(len(c))  # length of string

d = 'Python is awesome'
print(d.upper())  # convert to upper case
print(d.lower())  # convert to lower case

Output:

Hello, World!
Hello,Hello,Hello,
P
yth
6
PYTHON IS AWESOME
python is awesome

String Formatting

String formatting is used to create formatted strings. In Python, we can use the format() method to format strings. We can specify placeholders in a string using curly braces {} and pass values to those placeholders using the format() method.

Here's an example:

# Example of string formatting
x = 'John'
y = 'Doe'
z = 'My name is {} {}.'.format(x, y)
print(z)

Output:

My name is John Doe.

We can also use f-strings to format strings in Python 3.6 and above:

# Example of f-string
x = 'John'
y = 'Doe'
z = f'My name is {x} {y}.'
print(z)

Output:

My name is John Doe.

We have covered the basics of Python Strings in this tutorial.

Explore Tech Guide:

Codzify Logo

Terms and Conditions    Cookie Policy   Refund Policy   Adsense Disclaimer

Contact: teamcodzify@gmail.com