Strings

Learn everything about strings in Python, how to create, access, slice, and manipulate them using built-in methods like upper(), split(), join(), format(), and more.

Loading...
Strings

A string is a sequence of characters enclosed between single or double quotation marks. Strings are one of the most common data types in Python and can contain letters, numbers, symbols, or even spaces.

Creating Strings

name = "John Doe"
print(name)
 
message = "Hello, World!"
print(message)

If you want to print a statement with quotation marks in between the strings. Then you can use single quotes for convenience. For example:

print('He said, "I love Python programming"!')

Multiline Strings

You can create multiline strings by using triple single or triple double quotes. For example:

string = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(string)
 
string1 = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(string1)

Accessing Characters in a String

String is like an array of characters in python. You can access characters of string by using its index which starts from 0.

message = "Hello, World!"
print(message[0]) #output: H
print(message[1]) #output: e
print(message[5]) #output: ,

Length of a String

You can use the len() function to find the length of a string.

message = "Hello, World!"
messageLength = len(message)
print(messageLength) #Output: 13

String Slicing

String is like an array of characters, so you can extract a part of a string using slicing.

message = "Hello, World!"
 
# Extract characters from index 0 to index 5 (including 0 but not 5)
print(message[0:5])  # Output: "Hello"
 
# Omitting start index (defaults to 0) (including 0 but not 5)
print(message[:5])   # Output: "Hello"
 
# Extract characters from index 3 to the end
print(message[3:])   # Output: "lo, World!"
 
# Slicing using negative index
print(message[0:-3])  # Output: "Hello, Wor"
# Python interprets above code as print(message[0:len(message)-3])
 
print(message[-1:]) # Output: "!"
# Python interprets above code as  print(message[len(message)-1:])

Looping Through a String

Strings are iterable, so you can loop through each character in the string.

message = "Hello, World!"
for i in message:
    print(i)

String Methods

Python provides several built-in methods for working with strings:

  • upper() : The upper() method converts a string to upper case.

    message = "Hello, World!"
    print(message.upper()) #Output: HELLO, WORLD!
  • lower(): The lower() method converts a string to lower case.

    message = "Hello, World!"
    print(message.lower()) #Output: hello, world!
  • capitalize() : The capitalize() method converts the first character of the string to uppercase and the rest other characters of the string to lowercase.

    message = "hello, World!"
    print(message.capitalize()) #Output: Hello, world!
  • split() : The split() method splits the given string and returns the separated strings as list items.

    message = "Hello, World!"
    print(message.split(" ")) #Output: ['Hello,', 'World!']
  • strip() : The strip() method removes white spaces at the beginning and end of the string.

    message = " Hello, World! "
    print(message.strip()) #Output: Hello, World!
  • rstrip() : The rstrip() removes any trailing characters.

    message = " Hello, World! "
    print(message.rstrip("!")) #Output: Hello, World
  • replace() : The replace() method replaces all occurrences of a string with another string.

    message = "Hello, World!"
    print(message.replace("Hello", "Hi")) #Output: Hi, World!
  • center() : The center() method aligns the string to the center as per the parameters given by the user.

    message = "Hello, World!"
    print(message.center(50))  # Output: "                Hello, World!                "

    You can also provide padding character.

    message = "Hello, World!"
    print(message.center(50,"!")) #Output:!!!!!!!!!!!!!!!!!!Hello, World!!!!!!!!!!!!!!!!!!!!
  • count() : The count() method returns the number of times the given value has occurred within the given string.

    message = "Hello, World!"
    print(message.count("l")) #Output: 3
  • title() : The title() method capitalizes first letter of each word within the string.

    message = "Python is a programming language"
    print(message.title()) #Output: Python Is A Programming Language
  • startswith() : The startswith() method checks if the string starts with a given value. It gives result in true or false.

    message = "Hello, World!"
    print(message.startswith("Hello")) #Output: True
  • endswith(): The endswith() method checks if the string ends with a given value. It gives result in true or false.

    message = "Hello, World!"
    print(message.endswith("!")) #Output: True
  • find() : The find() method searches for the first occurrence of the given value and returns the index where it is present. If given value is absent from the string then return -1.

    message = "Hello, World!"
    print(message.find("W")) #Output: 7
    print(message.find("a")) #Output: -1
  • index() : The index() method searches for the first occurrence of the given value and returns the index where it is present. If given value is absent from the string then raise an exception.

    message = "Hello, World!"
    print(message.index("W")) #Output: 7
    print(message.index("a")) #Output: ValueError: substring not found

    This method is somewhat similar to the find() method. The major difference being that index() raises an exception if value is absent whereas find() return -1.

  • isalnum() : The isalnum() method returns True if the string consists only of A-Z, a-z, 0-9. If any other characters or punctuations are present, then it returns False.

    message = "Hello, World!"
    print(message.isalnum()) #Output: False
     
    message2 = "HelloWorld"
    print(message2.isalnum()) #Output: True
  • isalpha() : The isalpha() method returns True if the string consists only of A-Z, a-z. If any other characters or punctuations or numbers(0-9) are present, then it returns False.

    message = "Hello, World!"
    print(message.isalpha()) #Output: False
     
    message2 = "HelloWorld"
    print(message2.isalpha()) #Output: True
  • isupper() : The isupper() method returns True if all the characters in the string are upper case, else it returns False.

    message = "Hello, World!"
    print(message.isupper()) #Output: False
  • islower() : The islower() method returns True if all the characters in the string are lower case, else it returns False.

    message = "hello, world!"
    print(message.islower()) #Output: True
  • isprintable() : The isprintable() method returns True if all the values within the given string are printable (i.e., not whitespace, control characters, etc.), if not, then return False.

    message = "hello, world!"
    print(message.isprintable()) #Output: True
  • isspace() : The isspace() method returns True if the string consists white spaces, else returns False.

    message = "    "
    print(message.isspace()) #Output: True
  • istitle() : The istitle() method returns True if the first letter of each word of the string is capitalized, else it returns False.

    message = "World Health Organization" 
    print(message.istitle()) #Output: True
  • swapcase() : The swapcase() method changes the character casing of the string. Upper case are converted to lower case and lower case to upper case.

    message = "Hello, World!"
    print(message.swapcase()) #Output: hELLO, wORLD!

Support my work!