what is string in python
A string in Python is a data type used to store and work with text.
Quick Scoop
- A string is a sequence of characters (letters, digits, symbols, spaces) written inside quotes, like
"Hello"or'123!'.
- Python has no separate “char” type; a single character like
'a'is just a string of length 1.
- Strings are immutable: you cannot change them in place; any “change” creates a new string.
- You can create strings with single quotes, double quotes, or the
str()function:str(123)→"123".
Tiny example
python
text = "Hello, World!"
print(text[0]) # 'H'
print(len(text)) # 13
print(text.lower()) # 'hello, world!'
Mini sections
How to create a string
- Using quotes:
name = "Alice"greeting = 'Hi there'
- Using
str()to convert other data types:age_str = str(25)→"25"
Common things you do with strings
- Get length:
len(text)returns how many characters are in the string.
- Indexing:
text[0]gives the first character,text[-1]the last.
- Slicing:
text[0:5]gets a substring (e.g.,"Hello"from"Hello, World!").
- Changing case:
text.lower(),text.upper(),text.title().
- Cleaning spaces:
text.strip()removes leading and trailing whitespace.
- Splitting and joining:
"a,b,c".split(",")→["a", "b", "c"]"-".join(["2025", "10", "30"])→"2025-10-30"
String formatting (very common in real projects)
-
format()method:python
user = "alice" id_val = 321 msg = "User: {user} | Id: {id:08d}".format(user=user, id=id_val)
'User: alice | Id: 00000321'
-
f-strings (modern, very popular):
python
user = "alice" id_val = 321 msg = f"User: {user} | Id: {id_val:08d}"
These are used everywhere in current Python codebases to build readable messages, logs, and UI text.
A quick “story” example
Imagine you’re building a tiny preview feature for user posts. You might:
python
user_input = "This is a very long comment that should be shortened."
preview = (user_input[:10] + "...") if len(user_input) > 10 else user_input
print(preview) # 'This is a ...'
Here you are slicing a string (user_input[:10]), checking its length, and
building a new string with "..."—all classic string operations.
TL;DR: In Python, a string is an immutable sequence of characters used to
represent and manipulate text, created with quotes or str(), and comes with
many handy methods for everyday text handling.
Information gathered from public forums or data available on the internet and portrayed here.