In Python, strings are a built-in data type used to store sequences of characters. Strings are immutable, meaning that once they are created, their contents cannot be changed—any modification to a string results in a new string being created. This article present top usage python examples for string.
![tuple](https://codeblockhub.com/wp-content/uploads/2023/08/tuple-jpg.webp)
Python examples for string
Creating Strings
You can create a string by enclosing characters in single (' '
) or double (" "
) quotes. Triple quotes (''' '''
or """ """
) are used for multiline strings.
Here are 10 coding examples for string-related tasks in Python:
- String Concatenation:
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # Output: Hello World
- String Length:
string = "Python is awesome"
length = len(string)
print(length) # Output: 18
- String Splitting:
sentence = "This is a sample sentence."
words = sentence.split()
print(words) # Output: ['This', 'is', 'a', 'sample', 'sentence.']
- String Joining:
words = ['Hello', 'World']
sentence = ' '.join(words)
print(sentence) # Output: Hello World
- String Case Conversion:
text = "Python Programming"
lower_text = text.lower()
upper_text = text.upper()
print(lower_text) # Output: python programming
print(upper_text) # Output: PYTHON PROGRAMMING
- String Replacement:
sentence = "I like apples."
new_sentence = sentence.replace('apples', 'bananas')
print(new_sentence) # Output: I like bananas.
- String Searching:
text = "Python is powerful"
if 'powerful' in text:
print("Found")
else:
print("Not found")
- String Formatting:
name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
- Removing Whitespace:
text = " Some spaces here "
stripped_text = text.strip()
print(stripped_text) # Output: "Some spaces here"
- Substring Extraction:
string = "Hello, World!"
substring = string[7:12]
print(substring) # Output: World