In Python, string (str) is a built-in data types. a string data type is used to represent text. It’s a sequence of characters enclosed within either single quotes (‘ ‘) or double quotes (” “).
Below are some detailed properties of python string
- Text Representation: Strings in Python are used to represent text data. it can contain letters, numbers, symbols, and spaces.
- Enclosed in Quotes: Strings are enclosed within either single quotes (‘ ‘) or double quotes (” “). Both types have the same meaning, but it’s essential to enclose text within the same type of quotes. Mixing quotes, such as (‘ ” or ” ‘), isn’t allowed when defining a string.
- Immutable: In Python string data type is a immutable data types means Once a string is created, it cannot be changed. we can create new strings based on existing ones, but we can’t modify the original string directly.
- Sequence of Characters: A string is essentially a sequence of characters. Each character in the string has a specific position, starting from index 0.
- Length: we can find the length of a string using the
len()
function, which returns the number of characters in the string. - Concatenation: Strings can be concatenated using the
+
operator to combine them into a single string. - Indexing and Slicing: we can access individual characters within a string using indexing, e.g.,
my_string[0]
gives the first character. we can also slice strings to extract substrings, e.g.,my_string[1:4]
returns characters from index 1 to 3. - Escape Characters: Python supports escape characters like
\n
for newline and\t
for tab within strings. - String Methods: Python provides a variety of built-in methods to manipulate strings, such as
upper()
,lower()
,strip()
,replace()
,split()
, and many more. - Unicode Support: Python strings fully support Unicode, allowing us to work with characters from various languages and scripts.
Examples
Single Quotes (”) and Double Quotes (“”) String
Define strings using single or double quotes.
# Using single quotes name_single = 'Rajesh' # Using double quotes name_double = "Priya" print(name_single) print(name_double)
Triple Quotes String(”’ ”’ or “”” “””):
Define multi-line strings or strings with single/double quotes inside.
# Using triple single quotes quote_single = '''India is a diverse country.''' # Using triple double quotes quote_double = """Mumbai is the financial capital of India.""" print(quote_single) print(quote_double)
Concatenation of string
Combine two or more strings together.
first_name = 'Kunal' last_name = 'Sharma' full_name = first_name + ' ' + last_name print(full_name) # Output: Kunal Sharma
String Formatting
Insert variable values or expressions into strings for dynamic content.
city = 'Delhi' temperature = 40 # Using f-strings (formatted string literals) weather_report = f'Today in {city}, the temperature is {temperature} degrees Celsius.' print(weather_report)
String Indexing and Slicing
Access individual characters or portions of a string using their positions.
name = 'Neha' # Accessing individual characters first_char = name[0] last_char = name[-1] # Slicing part_of_name = name[1:3] print(first_char) # Output: N print(last_char) # Output: a print(part_of_name) # Output: eh
String Methods
Perform few operations like changing case, finding substrings, replacing text, etc., on strings.
sentence = 'Python programming is fun' # Changing case uppercase_sentence = sentence.upper() lowercase_sentence = sentence.lower() # Finding substrings position = sentence.find('programming') # Replacing substrings new_sentence = sentence.replace('Python', 'Java') print(uppercase_sentence) print(lowercase_sentence) print(position) print(new_sentence)
String Formatting with format()
Function
Another method for string formatting, particularly useful for multiple substitutions or formatting numbers.
name = 'Rahul' age = 25 # Using format() method info = 'My name is {} and I am {} years old.'.format(name, age) print(info)
String Splitting and Joining
Split strings into a list of substrings based on a delimiter or join a list of strings into a single string.
sentence = 'India is a beautiful country' # Splitting words = sentence.split() # Joining new_sentence = '-'.join(words) print(words) print(new_sentence)
Get Length of String
Find the number of characters in a string.
name = 'Dolly' # Finding length of string length = len(name) print(length) # Output: 5
Finding Substrings in a String
finding if a specific substring exists within a string
city = 'Bangalore' # Checking if substring exists if 'lore' in city: print('Yes, "lore" is present in Bangalore.') else: print('Substring not found.')
Removing Whitespaces from String
Remove leading and trailing whitespaces from a string.
address = ' Dell Domlur Road, Bangalore ' # Removing leading and trailing whitespaces clean_address = address.strip() print(clean_address)
Checking Start and End of a String
Check if a string starts or ends with a specific substring.
word = 'Himalaya' # Checking if string starts with if word.startswith('Him'): print('Yes, starts with "Him".') # Checking if string ends with if word.endswith('aya'): print('Yes, ends with "aya".')
Counting Substrings in a String
Count the occurrences of a substring within a string.
sentence = 'She sells seashells by the seashore' # Counting occurrences of substring count = sentence.count('se') print(count) # Output: 3
Reversing a String
Reverse the characters in a string.
name = 'School247' # Reversing string reversed_name = name[::-1] print(reversed_name) # Output: 742loohcS
Checking Alphanumeric in a String
Check if a string contains only alphanumeric characters.
username = 'school247' # Checking if alphanumeric if username.isalnum(): print('Username is alphanumeric.') else: print('Username contains non-alphanumeric characters.')
Capitalizing Words of String
Capitalize the first letter of each word in a string.
title = 'bhagat singh is the great indian freedom fighter' # Capitalizing words title_case = title.title() print(title_case) # Output: Bhagat Singh Is The Great Indian Freedom Fighter
Checking Case in a String
Check if a string is all uppercase, lowercase, or title case
name = 'SCHOOL' # Checking if uppercase if name.isupper(): print('Name is in uppercase.') else: print('Name is not in uppercase.')