Strings are sequences of Unicode characters. You can write them with single quotes, double quotes, or triple quotes for multiline strings:
single = 'Hello'
double = "World"
triple = """This spans
multiple lines"""
also_triple = '''This works too'''
Slicing extracts a portion using [start:stop:step]:
text = "Python"
print(text[0:2]) # Py
print(text[:3]) # Pyt
print(text[2:]) # thon
print(text[::-1]) # nohtyP (reverse)
print(text[::2]) # Pto (every other)
Strings are immutable — you cannot change a character in place:
s = "hello"
# s[0] = "H" # TypeError!
s = "H" + s[1:] # "Hello" — creates a new string
full = "Hello" + " " + "World" # "Hello World"
line = "-" * 20 # "--------------------"
print("Hey" * 3) # HeyHeyHey
name = "Alice"
age = 30
print(f"{name} is {age} years old")
print(f"{name!r}") # repr of name
print(f"{age:04d}") # "0030"
print("{} is {} years old".format("Bob", 25))
print("{1} is {0} years old".format(25, "Bob"))
print("%s is %d years old" % ("Charlie", 35))
newline = "Line1\nLine2" # newline
tabbed = "Col1\tCol2" # tab
quote = "She said \"Hi\"" # double quote
backslash = "C:\\Users\\name" # backslash
Use raw strings with r"..." to ignore escape sequences:
path = r"C:\Users\name" # no escaping needed
text = " Hello, World! "
text.upper() # " HELLO, WORLD! "
text.lower() # " hello, world! "
text.strip() # "Hello, World!"
text.split(",") # [" Hello", " World! "]
",".join(["a","b","c"]) # "a,b,c"
text.replace("World", "Python") # " Hello, Python! "
text.find("World") # 8
text.count("l") # 3
text.startswith(" He") # True
text.endswith("! ") # True
"hello".isalpha() # True
"123".isdigit() # True
"abc123".isalnum() # True
" ".isspace() # True
"Hello".istitle() # True
.format() and the % operator.
Write a program that asks the user for a sentence. Print the number of characters, words, and vowels in the sentence. Then reverse the sentence word-by-word (e.g. "Hello world" → "world Hello"). Finally, replace all vowels with * and print the result.