How to Construct a String in Python?

Estimated read time 1 min read

In Python, a string is a sequence of characters enclosed in either single quotes (”) or double quotes (“”). You can construct a string in several ways:

  1. Using quotes: You can directly assign a string value by enclosing it in quotes. For example:
my_string = 'Hello, World!'
  1. Using concatenation: You can concatenate (combine) multiple strings using the + operator. For example:
greeting = 'Hello'
name = 'Alice'
message = greeting + ', ' + name + '!'
  1. Using the str() function: You can convert other data types into strings using the str() function. For example:
age = 25
age_string = str(age)
  1. Using formatted strings (f-strings): Introduced in Python 3.6, f-strings provide a concise way to embed expressions inside string literals. They are prefixed with the letter f and curly braces {} are used to enclose expressions. For example:
name = 'Bob'
age = 30
greeting = f"Hello, my name is {name} and I am {age} years old."

These are some of the common ways to construct strings in Python. Remember that strings are immutable, which means you cannot change their characters once they are created. However, you can create new strings by applying various string manipulation methods and operations.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply