DEV Community

Cover image for Strings in Python
Karthick (k)
Karthick (k)

Posted on

Strings in Python

What Are Strings in Python?

A string is a sequence of characters enclosed in quotes. Characters can be letters, digits, symbols, spaces, or even special characters like newlines. In Python, strings are one of the most commonly used data types because almost every program deals with text in some form: names, messages, file paths, user input, and more.

Python treats strings as sequences, which means each character has a position (index), and you can access individual characters, extract substrings, and iterate over them just like you would with a list of items.

python
#1. String Indexing

name="python"

#3. String Immutability

# Strings in Python are immutable; once a string is created, you can't change any character in it. 
# If you try to assign a character anew to a specific index, Python raises a TypeError.abs
#4. String Methods

# Python provides a rich set of built-in methods for string manipulation. 
# These methods do not modify the original string cause strings are immutable; they return a new string.

python
#5. f-Strings (Formatted String Literals)
# Introduced in Python 3.6, f-strings are the most readable way to embed expressions inside the string
# Prefix the string with af andplace expressions inside curly braces {}.
Enter fullscreen mode Exit fullscreen mode

name="Rohan"
age=16;

print(f'{name} is {age} year old')


#String Creation and Indexing
single="hello"
double="hello"

triple='''this is a multi-line string'''

print(single==double)
print(triple)

name="Ananya"

print(name[0])
print(name[-1])
print(name[3])
print(name[-2])
Enter fullscreen mode Exit fullscreen mode
#String Immutability
name = "Vikram"

# Attempting to change a character causes an error
try:
    name[0] = "v"
except TypeError as e:
    print("Error:", e)


name = "u" + name[:-1]
print("New string:", name)


# Another approach using replace()
original = "LockeshKanagaraj"
modified = original.replace("LockeshKanagaraj", "KockeshKanagaraj")
print("Replace result:", modified)
print("Original unchanged:", original)
Enter fullscreen mode Exit fullscreen mode
#Essential String Methods

text = "  Hello, World!  "


print(text.strip())

print()
print(text.lstrip())
print(text.rstrip())


name = "aarav sharma"

print(name.upper())
print(name.title())
print(name.capitalize())

sentence = "Python is fun and Python is powerful"

print(sentence.count(
    'powerful'
))

print(sentence.find("and"))
print(sentence.find("karhtic"))

print()

print(sentence.replace("and","king is"))

Enter fullscreen mode Exit fullscreen mode
# split() - break string into a list
sentence = "Maths Science English Hindi"
words = sentence.split()
print(words)


csv_data = "Aarav,Priya,Rohan,Meera"

name=csv_data.split()
print(name)

result="-".join(name)
print(result)


print()

letters = ['P', 'y', 't', 'h', 'o', 'n']
word=''.join(letters)
print(word)

## split with maxsplit

data="one:two:three:four"
print(data.split(":",2))
Enter fullscreen mode Exit fullscreen mode
#f-Strings and .format()

name="priyaa"

marks=92.567;


print(f'Student:{name}')
print(f'Marks : {marks:.2f}')
print(f"Double marks: {marks * 2}")
print(f"Name in uppercase: {name.capitalize()}")

print()
# .format() method
print("Hello, {}! You scored {}%.".format("Rohan", 85.000))
print("Pi is {:.4f}".format(3.14159))
print("{0} and {1} and {0}".format("Coding", "Maths"))


# Padding and alignment with f-strings
for i in range(1, 4):
    print(f"{i:>5} | {i*i:<5} | {i*i*i:^5}")

Enter fullscreen mode Exit fullscreen mode
#Checking Methods and ord()/chr()


print("12345".isdigit())

print("12.4".isdigit())

print("Hehl2lo".isalpha()) 

print("abc123".isalnum()) 

print("Python3".startswith("Py"))
print("script.py".endswith(".py"))



print()

# ord() and chr()
print(ord('A'))   # 65
print(ord('a'))   # 97
print(chr(65))    # A
print(chr(97))    # a
print(ord('0'))   # 48
print(chr(199))

print()
# Character arithmetic
letter = 'C'
next_letter = chr(ord(letter) + 1)
print(f"Next letter after {letter} is {next_letter}")

Enter fullscreen mode Exit fullscreen mode
#String Multiplication and Concatenation


line="="*40

print(line)

pattern="AB"*6 
print(pattern)

# Concatenation
first = "Modern"
last = "Coders"
full = first + " Age " + last
print(full)


name = "Aarav"
age = 14
# This causes an error: name + " is " + age
# Fix with str():
result = name + " is " + str(age)
print(result)
print(f"{name} is {age}")
Enter fullscreen mode Exit fullscreen mode

Top comments (0)