0% found this document useful (0 votes)
16 views2 pages

Python String Manipulation Guide

Uploaded by

tutor b
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views2 pages

Python String Manipulation Guide

Uploaded by

tutor b
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Strings and Their Manipulation

What is a String in Python?

A string in Python is a sequence of characters enclosed in either single quotes '...' or double
quotes "...". Strings can include letters, numbers, symbols, and whitespace. They are
immutable, meaning you cannot change the original string directly, but you can create new
strings based on it. Characters in a string are accessed using an index. An index is a numerical
position that identifies the location of an element within a sequence. In most programming
languages, indexing starts at 0.

 The first element is at index 0, the second at index 1, and so on.


 Negative indices (in some languages like Python) count from the end, e.g., -1 is the last
element.

Example with a string in Python:

s = "hello"
print(s[0]) # 'h' → first character
print(s[-1]) # 'e' → second character

Further Example:

text = "Hello, Python!"

Common Python String Manipulation Syntax


Operation Syntax Example Output
Access string[index] text[0] 'H'
character
Slice string string[start:end] text[0:5] 'Hello'
Slice with step string[start:end:step] text[0:10:2] 'HloP'
Length len(string) len(text) 13
Concatenate string1 + string2 "Hello" + " World" 'Hello World'
Repeat string * n "Hi" * 3 'HiHiHi'
Uppercase [Link]() "hello".upper() 'HELLO'
Lowercase [Link]() "HELLO".lower() 'hello'
Title Case [Link]() "hello world".title() 'Hello World'
Strip [Link]() " text ".strip() 'text'
whitespace
Replace [Link](old, "Hello".replace("H", 'Jello'
substring new) "J")
Split string [Link](separator) "a,b,c".split(",") ['a','b','c']
Check substring in string 'Hello' in text True
substring
Find substring [Link](substring) [Link]("Python") 7
Count [Link](substring) [Link]("o") 2
occurrences

You might also like