Topic 12: String Data Type in Python?


πŸ‘ˆPrevious Topic                                                                                 String Quiz  NextπŸ‘‰  

String Data Type

                                                       (Reading time   7-10minutes)
In Python, a string is a sequence of characters enclosed within single quotes (‘ ’), double quotes (“ ”), or even triple quotes (‘’’ ’’’ or “”” “””).

Strings are one of the most commonly used data types because they help store and manipulate textual information  such as names, messages, or file paths.

Example:

# Defining strings
str1 = 'Hello'
str2 = "Python Programming"
str3 = '''Welcome to world of Python!'''

print(str1)
print(str2)
print(str3)

Output:

Hello
Python Programming
Welcome to world of Python!

Characteristics of Strings

  • Strings are immutable, meaning once created, they cannot be changed.

  • They support indexing and slicing.

  • Strings can be concatenated and repeated using operators.

  • Python provides many built-in functions to manipulate strings.

String Operators in Python

Python supports various operators to work with string data.

https://procureshaft.com/wzgumvjyws?key=4971ef9cacd06487562e3b50fff4707f
Operator Description Example Output
+ Concatenation 'Hello' + ' World' 'Hello World'
* Repetition 'Hi' * 3 'HiHiHi'
[] Indexing name[0] First character
[start:end] Slicing name[0:4] Substring
in Membership 'P' in 'Python' True
not in Non-membership 'x' not in 'Python' True
== Equality check 'abc' == 'abc' True
<, >, <=, >= Comparison (lexicographic) 'a' < 'b' True
String data type in Python

 Example:

s1 = "Hello"
s2 = "World"

print(s1 + " " + s2)     # Concatenation
print(s1 * 3)            # Repetition
print(s1[1])             # Indexing
print(s1[1:4])           # Slicing
print('H' in s1)         # Membership
print(s1 == "Hello")     # Comparison

Output:

Hello World
HelloHelloHello
e
ell
True
True

String Functions in Python

Python provides a rich set of built-in string methods for manipulation and analysis.

Function / Method Description Example Output
len() Returns length of string len("Python") 6
.lower() Converts to lowercase "HELLO".lower() 'hello'
.upper() Converts to uppercase "hello".upper() 'HELLO'
.title() Converts first letter of each word to uppercase "python programming".title() 'Python Programming'
.capitalize() Capitalizes first character "python".capitalize() 'Python'
.strip() Removes leading/trailing spaces " hello ".strip() 'hello'
.replace(a, b) Replaces substring a with b "hello".replace("h","H") 'Hello'
.find(sub) Returns index of first occurrence "python".find("th") 2
.count(sub) Counts occurrences of substring "banana".count("a") 3
.split() Splits string into list "a,b,c".split(",") ['a', 'b', 'c']
.join(list) Joins list elements with separator ",".join(['a','b','c']) 'a,b,c'
.startswith() Checks if string starts with substring "python".startswith("py") True
.endswith() Checks if string ends with substring "python".endswith("on") True
.isalnum() Checks if all chars are alphanumeric "abc123".isalnum() True
.isalpha() Checks if all chars are alphabetic "abc".isalpha() True
.isdigit() Checks if all chars are digits "123".isdigit() True

Example:

text = "  Welcome to Python Programming  "

print(len(text))
print(text.lower())
print(text.upper())
print(text.strip())
print(text.replace("Python", "AI"))
print(text.split())

Output:

35
  welcome to python programming  
  WELCOME TO PYTHON PROGRAMMING  
Welcome to Python Programming
  Welcome to AI Programming  
['Welcome', 'to', 'Python', 'Programming']

String Indexing and Slicing

Strings are sequences, so each character has an index number starting from 0.

P  y  t  h  o  n
0  1  2  3  4  5

Indexing Example:

s = "Python"
print(s[0])   # First character
print(s[-1])  # Last character

Output:

P
n

 Slicing Example:

print(s[0:4])   # First four characters
print(s[:3])    # From start to index 2
print(s[2:])    # From index 2 to end

Output:

Pyth
Pyt
thon

String Immutability

Strings in Python cannot be changed after creation.
If you try to modify a string directly, Python creates a new one instead.

Example:

s = "Hello"
# s[0] = 'h'       Invalid (cannot modify string directly)
s = "h" + s[1:]    Correct way
print(s)

Output:

hello

Summary

Concept                                Explanation
Definition   Sequence of characters enclosed in quotes
Type                                       Immutable
Operators  +, *, in, [], [start:end], ==, <, >
Important Methods   .upper(), .lower(), .replace(), .split(), .join(), .find()
Use Case   Text processing, data cleaning, file handling, natural language processing

The string data type in Python is one of the most powerful and flexible data types. With its vast set of operators and functions, strings allow developers to handle text data easily from simple messages to complex natural language processing tasks.

πŸ‘ˆPrevious Topic                                                            String Quiz  NextπŸ‘‰ 


Comments

Popular posts from this blog

Topic1 :- What is Python Programming?

Topic2: -Why Python?

Topic7: What is Numpy?