Python Strings


Strings

Single or double quotation marks are used to surround strings in Python.

'hello' is the same as "hello".

Example :- The print() function allows you to show a literal string :

#You can use double or single quotes:

print("Hello")
print('Hello')

Output :-

Hello
Hello

You can also search for these topics, python string programs and format, python contains and reverse string, define the python list to string, python remove character from string, what is a python sting, what is python string format, how to replace in python string, python string assignment, python string based programs.

Assign String to a Variable

The variable identity is assigned to a string guided by the same sign and string :

Example :-

a = "Hello"
print(a)

Output :-

Hello

You can also search for these topics, python assign string to variable name, assign string multiple variable in python, python assign formatted string to variable, assign empty string to variable in python, how to assign part of string to variable using python, how do you assign a string to a variable in python, python assign string to a variable example.

Multiline Strings

While using three quotes, you can set a multiline string to a variable :

Example 1 :- You can use three double quotes :

a = """First Line,
Second Line,
Last Line."""

# Or three single quotes

a = '''First Line,
Second Line,
Last Line.'''

print(a)

Output :-

First Line,
Second Line,
Last Line.

Note : the line cuts are inserted at the same location as the script in the consequence.

You can also search for these topics, python multiline strings with variables, multiline strings with format in python, list the python multiline strings, how can you create multiline string in python, compare multiline string using python, execute the key error with python multiline strings, example for python multiline strings.

Strings are Arrays

Strings are arrays of bytes in Python that represent unicode characters like most other popular programming language.

However, Python has no data type, but only one character is a string with a length of 1.

Brackets can be used for accessing string elements.

Example :- Have the position 1 character (remember that position 0 for the first character) :

a = "Hello, World!"
print(a[1])

Output :-

e

You can also search for these topics, python string array define, declare the strings are arrays in python, example for python strings are arrays, python strings in key array, merge the strings are arrays using python, how to remove the strings from array.

Looping Through a String

Because strings are arrays, we can use a for loop to iterate through the characters in a string.

Example :- Loop through the letters in the word "banana" :

for x in "banana":
  print(x)

Output :-

b
a
n
a
n
a

You can also search for these topics, python loop through string characters and elements, python for loop on a string, get python looping through a string, python how to loop through a string, loop through a string in python, list the looping through string using python.

String Length

Example :- Can use len() function to obtain a string length :

a = "Hello, World!"
print(len(a))

Output :-

13

You can also search for these topics, python string length limit, count the python string element, string length without spaces in python, python in bytes with string length 0, format the string length using python, what is maximum length of a string in python, what is string length in python

Check String

We can use the keyword in to see if a specific phrase or character is present in a string.

Example :- Examine the following text to see if the word "free" appears :

txt = "The best things in life are free!"
print("free" in txt)

Output :-

True

In an if statement, you can use it as follows :

Example 2 :- Print only if "free" is present :

txt = "The best things in life are free!"
if "free" in txt:
  print("Yes, 'free' is present.")

Output :-

Yes, 'free' is present.

You can also search for these topics, python check string starts with, string is number in python, check the string end with python, check the equality of python, how to contains python check string, check what string starts with python, how to check if a string is a number python, Example for check string in python.

Check if NOT

We can use the keyword not in determine if a certain sentence or character does NOT appear in a string.

Example 1 :- Examine the following text to see if the word "expensive" is missing :

txt = "The best things in life are free!"
print("expensive" not in txt)

Output :-

True

Use it in an if statement :

Example 2 :- print only if "expensive" is NOT present :

txt = "The best things in life are free!"
if "expensive" not in txt:
  print("No, 'expensive' is NOT present.")

Output :-

No, 'expensive' is NOT present.

You can also search for these topics, python check if not none, python check if not null, check if not equal using python, check if not number using python, python check if not string, check if not empty in python, check python if not nan, Example for python check if NOT.

Python Slicing - Extract Substring or Part of String

The slice syntax allows you to return a range of characters.

Specify the start index and end index, separated by a colon(:), to return a section of the string.

Example 1 :- Figure out where each character is located between positions 2 and 5 :

b = "Hello, World!"
print(b[2:5])

Output :-

llo

Note :- The end index will not be included in the output.

Note :- It's important to note that the first character has an index of 0.

Slice From the Start

The range will begin at the first character if the start index is not specified.

Example 2 :- Get the characters from the beginning to position 5 :

b = "Hello, World!"
print(b[:5])

Output :-

Hello

Slice To the End

Example 3 :- Leaving out the end index will cause the range to go to the end of the range :

b = "Hello, World!"
print(b[2:])

Output :-

llo, World!

Negative Indexing

Example 4 :- Slices can be started from the end of the string by using negative indexes :-

b = "Hello, World!"
print(b[-5:-2])

Output :-

orl

You can also search for these topics, python slicing strings example, how to reverse a string in python using slicing, python slice string untill characters, python slice get start, python slice from the start example, python slice from middle to end, python slice beyond end, python list slice to end, negative indexing in python example, how does negative indexing work in python, positive and negative indexing in python.

Python - Modify Strings

Strings can be used with Python's built-in methods.

You can also search for these topics, python modify strings in dataframe, how to modify strings in python, python change string to date format, how to change strings to number in python, replace string python not working, Example for Python Modify Strings.

Python String - Lower Case and Upper Case

The lower() method is used to convert strings into lower case letter.

The upper() method is used to convert strings into upper case letter.

Example :-

a = "Hello, World!"
print(a.lower())
print(a.upper())

Output :-

hello, world!
HELLO, WORLD!

Strings are returned in lower case using the function lower() :

The upper() method returns a string that is all capital letters :

You can also search for these topics, python string uppercase example, method upper() using python, python string lowercase example, method lower() using python.

Remove Whitespace

The space before and/or after the actual text is known as whitespace, and it's fairly common to desire to get remove of it.

The strip() method is used to remove the spaces at beginning and/or end of the string.

A space may be a whitespace, Tab key, or Newline.

Example :- The following example will eliminate any spaces at beginnig or end of the string :

a = "   Hello, World!   "
print(a.strip())

Output :-

Hello, World!

You can also search for these topics, python remove whitespace from text file, how to remove extra whitespace in python, python remove whitespace before punctuation, eliminate whitespaces python, remove multiple whitespace python, Example for python Remove Whitespace.

Replace String

The replace() function is used replace a substring with another substring.

Example :-

a = "Hi Hello!"
print(a.replace("H", "J"))
print(a.replace("Hi", "Say"))

Output :-

Ji Jello!
Say Hello!

You can also search for these topics, python replace string with another string file, what does string replace do in python, what is python string format and python string replace, how to replace last character of string in python, python replace string with integer, Example for python Replace String.

Split String

A string can be splitted into multiple chunks using any separator.

A separator may be any character which is used to split the string into substrings.

With the split() method, you can create a list in which the text between separators is shown as list items.

Example :- It finds occurrences of the separator, the split() method breaks the string into substrings :

a = "Hello, World!"
b = a.split(",")
print(b)

m = "123-3736458";
print(m.split("-"))

Output :-

['Hello', ' World!']
['123', '3736458"

You can also search for these topics, python split string by character count, what does string split return python, how to split a string in python with delimiter, python split string after character, python split string conditional, Example for python Split String.

String Concatenation

The + operator can be used to concatenate or merge two strings.

Example 1 :- Variable a and variable b should be combined into variable c :

a = "Hello"
b = "World"
c = a + b
print(c)

Output :-

HelloWorld

Example 2 :- To create a space between them, add a " " before or after them :

a = "Hello"
b = "World"
c = a + " " + b
print(c)

Output :-

Hello World

You can also search for these topics, python string concatenation with format, what is the string concatenation operator in python, how to add space in string concatenation in python, string concatenation python multiple lines, string concatenation python example.

String Format

In python, We cannot combine a string and a number or other types.

Example 1 :- In the Python Variables chapter, we learnt that it is not possible to combine strings and numbers in this manner :

age = 36
txt = "My name is John, I am " + age
print(txt) 

Output :-

Traceback (most recent call last):
File "demo_string_format_error.py", line 2, in < module>
txt = "My name is John, I am " + age
TypeError: must be str, not int

The format() method allows us to combine texts and numbers together.

As a result, format() accepts a string as a parameter, formats it, and inserts its contents into the string where the placeholders {} are :

Example 2 :- To put numbers into strings, use the format() method :

age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

Output :-

My name is John, and I am 36

Example 3 :- Any number of arguments may be passed to the format() method, and they will be placed in the appropriate placeholders :

quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price)

Output :-

I want 3 pieces of item 567 for 49.95 dollars.

Example 4 :- In order to ensure that arguments are placed in the correct placeholders, utilise index numbers {0} :

quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

Output :-

I want to pay 49.95 dollars for 3 pieces of item 567

You can also search for these topics, python string format specifiers, what is python string format, how to use python string format, python string format keyerror, python string format length, Example for python String Format.

Escape Character

Use an escape character to insert characters that are illegal in a string.

After a backslash \, insert the character you want to escape.

A double quotation inside a string enclosed by double quotes is an example of an illegal character :

Example 1 :- Using double quotes within a double quote-enclosed string will result in an error :

txt = "We are the so-called "Vikings" from the north."

#You will get an error if you use double quotes inside a string that are surrounded by double quotes:

Output :-

File "demo_string_escape_error.py", line 1
txt = "We are the so-called "Vikings" from the north."
^
SyntaxError: invalid syntax

Use the escape character \" to remedy this problem :

Example 2 :- As a result of this escape character, you are able to utilise double quotes in places where you would not ordinarily be allowed :

txt = "We are the so-called \"Vikings\" from the north."
print(txt) 

Output :-

We are the so-called "Vikings" from the north

You can also search for these topics, python escape characters not working, unicode python escape characters, add python escape character, python remove escape characters from string, python string keep escape characters, Example for python string escape characters.