Python String

What is a String?

A string is a sequence of characters that can be enclosed in either single quotes (') or double quotes ("). In Python, strings are a fundamental data type represented by the class str.

s = 'aditya'
a = "aditya"

Both s and a are strings containing the text “aditya”. You can check the type of a variable in Python using the type() function, which confirms that s and a are of type str.

Let us see few of the built in function
Python provides several built-in functions to work with strings:

Accessing Strings:

# Positive indexing
s = 'hello'
print(s[0]) # Output: 'h'

# Negative indexing
print(s[-1]) # Output: 'o'

Slicing Strings:

s = 'Learning Python is fun!'
print(s[9:15]) # Output: 'Python'
print(s[:8]) # Output: 'Learning'
print(s[16:]) # Output: 'is fun!'

Finding Length:

s = 'amith'
print(len(s)) # Output: 5

Checking Membership:

y = 'amith'
print('a' in y) # Output: True
print('k' in y) # Output: False

String Comparison:

s1 = 'hello'
s2 = 'world'
print(s1 == s2) # Output: False
print(s1 < s2) # Output: True (lexicographical comparison)

Removing Spaces:

s = '  hello  '
print(s.strip()) # Output: 'hello'

Finding Characters in String:

s = 'hello'
print(s.find('e')) # Output: 1
print(s.find('x')) # Output: -1 (character not found)

Counting Substrings:

s = 'banana'
print(s.count('a')) # Output: 3

Replacing Strings:

s = 'hello world'
print(s.replace('world', 'python')) # Output: 'hello python'

Splitting Strings:

s = 'apple,banana,cherry'
print(s.split(',')) # Output: ['apple', 'banana', 'cherry']

Joining Strings:

t = ('sunny', 'bunny')
print('-'.join(t)) # Output: 'sunny-bunny'

Changing Case:

s = 'hello'
print(s.upper()) # Output: 'HELLO'
print(s.lower()) # Output: 'hello'
print(s.title()) # Output: 'Hello'

These examples demonstrate a variety of operations and functions that you can perform with strings in Python. Strings are incredibly versatile and are used extensively in programming for tasks like text processing, data manipulation, and more.

Leave a comment