Learn Python Programming  /  Data Structures  /  String

String

Strings hold text, and Python gives them a rich set of built-in methods — cleaning, splitting, and formatting text is something you will do constantly when preparing real data for analysis.

Creating and Indexing Strings

R Code
name = "Data Science"

print(name[0])       # first character
print(name[-1])      # last character
print(name[0:4])     # slice
print(len(name))
Output
D
e
Data
12

String Formatting with f-strings

f-strings (formatted string literals) are the modern, preferred way to build strings that include variable values.

R Code
name = "Rafi"
score = 88.456

message = f"{name} scored {score:.1f} points"
print(message)
Output
Rafi scored 88.5 points
💡 Tip
Inside an f-string, {score:.1f} formats the number to exactly 1 decimal place. Try :.2f, :,.0f (with thousands separators), or :.0% for a percentage - formatting specs like these save a lot of manual round()/str() work.

Common String Methods

R Code
text = "  Hello, World!  "

print(text.strip())        # remove leading/trailing whitespace
print(text.lower())        # lowercase
print(text.upper())        # uppercase
print(text.strip().replace("World", "Python"))
print("a,b,c".split(","))     # splits into a list
print("-".join(["2024","01","15"]))  # joins a list into one string
Output
Hello, World!
  hello, world!  
  HELLO, WORLD!  
Hello, Python!
['a', 'b', 'c']
2024-01-15

Checking String Content

R Code
email = "user@example.com"

print(email.startswith("user"))
print(email.endswith(".com"))
print("@" in email)
print("12345".isdigit())
Output
True
True
True
True

Advanced: Cleaning Messy Real-World Text

🚀 Advanced Example
Chaining string methods together is the standard way to clean survey responses or scraped data before analysis.
R Code
raw_responses = ["  Yes  ", "YES", "yes.", " No"]

cleaned = [r.strip().lower().rstrip(".") for r in raw_responses]
print(cleaned)
Output
['yes', 'yes', 'yes', 'no']

Key Points

  • Strings support indexing and slicing exactly like lists.
  • f-strings (f"{value}") are the modern way to build text that includes variable values, with format specs like :.1f.
  • Chain .strip(), .lower(), .replace() and similar methods together to clean messy real-world text.
  • .split() breaks a string into a list; "sep".join(list) does the reverse.