Here are 10 code examples to explain the usage of the string data type:
1. String data type Initialization
Strings can be initialized using single, double, or triple quotes.
str1 = 'Hello, World!'
str2 = "Python is fun."
str3 = '''Multi-line
string in Python.'''
print(str1)
print(str2)
print(str3)
2. String Concatenation
Use the +
operator to concatenate strings.
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # John Doe
3. String Repetition
Use the *
operator to repeat a string multiple times.
repeat_str = "ha" * 3
print(repeat_str) # haha
4. Indexing of String Data Type
Strings can be indexed to fetch characters at specific positions. Negative indexing starts from the end.
text = "Python"
print(text[0]) # P
print(text[-1]) # n
5. String Slicing
Extract a portion of the string using slicing.
text = "programming"
slice1 = text[1:4] # "rog"
slice2 = text[:4] # "prog"
slice3 = text[4:] # "ramming"
print(slice1, slice2, slice3)
6. String Length
Use the len()
function to get the length of a string.
message = "Hello, World!"
length = len(message)
print(length) # 13
7. String Methods
Strings come with built-in methods for various operations.
text = "hello world"
capitalized = text.capitalize()
upper_case = text.upper()
is_alpha = text.isalpha()
print(capitalized) # Hello world
print(upper_case) # HELLO WORLD
print(is_alpha) # False (because of space)
8. String Formatting
Format strings using the format()
method or f-strings (Python 3.6+).
name = "Alice"
age = 28
formatted_str1 = "{} is {} years old.".format(name, age)
formatted_str2 = f"{name} is {age} years old."
print(formatted_str1)
print(formatted_str2)
9. Escape Characters
Use backslashes to escape special characters in strings.
sentence = "She said, \"Python is my favorite language!\""
print(sentence)
10. Multi-line Strings and Raw Strings
Triple quotes allow for multi-line strings. Use r
or R
prefix for raw strings (ignores escape characters).
multi_line = '''This is a
multi-line
string.'''
print(multi_line)
path = r"C:\Users\Name\Documents"
print(path) # C:\Users\Name\Documents
These examples showcase various operations and features of strings in Python. Strings are versatile and come with numerous built-in methods that make text manipulation easy.