string

Top 10 simple Python examples for string usage

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

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:

  1. String Concatenation:
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result)  # Output: Hello World
  1. String Length:
string = "Python is awesome"
length = len(string)
print(length)  # Output: 18
  1. String Splitting:
sentence = "This is a sample sentence."
words = sentence.split()
print(words)  # Output: ['This', 'is', 'a', 'sample', 'sentence.']
  1. String Joining:
words = ['Hello', 'World']
sentence = ' '.join(words)
print(sentence)  # Output: Hello World
  1. 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
  1. String Replacement:
sentence = "I like apples."
new_sentence = sentence.replace('apples', 'bananas')
print(new_sentence)  # Output: I like bananas.
  1. String Searching:
text = "Python is powerful"
if 'powerful' in text:
    print("Found")
else:
    print("Not found")
  1. String Formatting:
name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
  1. Removing Whitespace:
text = "   Some spaces here   "
stripped_text = text.strip()
print(stripped_text)  # Output: "Some spaces here"
  1. Substring Extraction:
string = "Hello, World!"
substring = string[7:12]
print(substring)  # Output: World

Read also: