What Is String in Python? See Examples in detail

Strings in Python are used to store text data. A string is a sequence of characters enclosed within single quotes ' ' or double quotes " ".

Strings are one of the most commonly used data types in Python programming.


Why Strings Are Important

Strings are used to:

  • Store names, messages, and text
  • Handle user input and output
  • Process and analyze text data
  • Build real-world applications

Example:

message = "Hello Python"

Creating Strings in Python

name = "Sagar"
city = 'Delhi'

Both single and double quotes work the same way.


Accessing String Characters

Strings are indexed starting from 0.

text = "Python"
print(text[0])
print(text[-1])

String Slicing

text = "Python"
print(text[1:4])

Output:

yth

String Length

Use the len() function.

print(len(text))

Common String Methods

MethodDescription
upper()Converts to uppercase
lower()Converts to lowercase
strip()Removes spaces
replace()Replaces text
split()Splits string

Example:

text = "hello world"
print(text.upper())

String Concatenation

first = "Hello"
second = "World"
print(first + " " + second)

String Formatting

name = "Aman"
age = 25
print(f"My name is {name} and I am {age}")

Strings Are Immutable

Strings cannot be modified directly.

text[0] = "H"  # Error

Conclusion

Strings are fundamental in Python for handling text data. Mastering strings helps in building applications involving user input, data processing, and text analysis.


References

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *