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:
- Using quotes: You can directly assign a string value by enclosing it in quotes. For example:
my_string = 'Hello, World!'
- Using concatenation: You can concatenate (combine) multiple strings using the
+
operator. For example:
greeting = 'Hello'
name = 'Alice'
message = greeting + ', ' + name + '!'
- Using the
str()
function: You can convert other data types into strings using thestr()
function. For example:
age = 25
age_string = str(age)
- 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.
+ There are no comments
Add yours