What is a String and its types in Python?

What is a String in Python?

In Python, a string is a sequence of characters enclosed within single quotes ('), double quotes ("), or triple quotes (''' or """).

Example:

string1 = 'Hello' string2 = "World" string3 = '''Python''' string4 = """Programming""" 

Types of String Formats in Python

Python provides various ways to format and manipulate strings:

1. String Concatenation

Joining multiple strings using the + operator.

name = "Alice" greeting = "Hello, " + name + "!" print(greeting) # Output: Hello, Alice! 

2. String Formatting Methods

a) Using % Formatting (Old Method)

This method is similar to C-style string formatting.

name = "Alice" age = 25 print("Hello, %s! You are %d years old." % (name, age)) 
  • %s → String
  • %d → Integer
  • %f → Float

b) Using .format() Method

Introduced in Python 3, it allows inserting values in placeholders {}.

name = "Bob" age = 30 print("Hello, {}! You are {} years old.".format(name, age)) 

You can also specify index positions:

print("Hello, {1}! You are {0} years old.".format(age, name)) 

c) Using f-Strings (Python 3.6+)

f-Strings (formatted string literals) are the most efficient way to format strings.

name = "Charlie" age = 22 print(f"Hello, {name}! You are {age} years old.") 

They support expressions inside {}:

num1, num2 = 10, 20 print(f"Sum of {num1} and {num2} is {num1 + num2}.") 

3. Multi-line Strings

Using triple quotes (''' or """) for multi-line strings.

message = """Hello, This is a multi-line string. It spans multiple lines.""" print(message) 

4. Raw Strings (r'' or r"")

Used to prevent escape characters (\n, \t, etc.) from being interpreted.

path = r"C:\Users\Alice\Documents\file.txt" print(path) # Output: C:\Users\Alice\Documents\file.txt 

5. Byte Strings (b'')

Used for handling binary data.

byte_str = b"Hello" print(byte_str) # Output: b'Hello' 

6. Unicode Strings

Python 3 strings are Unicode by default, but you can explicitly define them:

unicode_str = u"Hello, Unicode!" print(unicode_str) 

7. Escape Sequences in Strings

Escape sequences allow inserting special characters:

new_line = "Hello\nWorld" # New line tab_space = "Hello\tWorld" # Tab space quote_inside = "She said, \"Python is great!\"" # Double quotes inside string 

8. String Methods

Python provides several built-in string methods:

s = " hello Python " print(s.upper()) # ' HELLO PYTHON ' print(s.lower()) # ' hello python ' print(s.strip()) # 'hello Python' (removes spaces) print(s.replace("Python", "World")) # ' hello World ' print(s.split()) # ['hello', 'Python'] 

Conclusion

Python provides multiple ways to handle and format strings, from basic concatenation to f-strings and .format(). f-Strings (f"") are generally the most recommended due to their efficiency and readability.

4 thoughts on “What is a String and its types in Python?

Leave a Reply