The Wayback Machine - https://web.archive.org/web/20240926212217/https://www.geeksforgeeks.org/python-string/
Open In App

Python String

Last Updated : 24 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A String is a data structure in Python Programming that represents a sequence of characters. It is an immutable data type, meaning that once you have created a string, you cannot change it. Python String are used widely in many different applications, such as storing and manipulating text data, representing names, addresses, and other types of data that can be represented as text.

What is a String in Python?

Python Programming does not have a character data type, a single character is simply a string with a length of 1. To explore more about Python String go through a free online Python course. Now, let’s see the Python string syntax:

Syntax of String Data Type in Python

string_variable = 'Hello, world!'

Example of string data type in Python

Python
string_0 = "A Computer Science portal for geeks"
print(string_0)
print(type(string_0))

Output:

A Computer Science portal for geeks
<class 'str'>

Create a String in Python

Strings in Python can be created using single quotes or double quotes or even triple quotes. Let us see how we can define a string in Python or how to write string in Python.

Example:

In this example, we will demonstrate different ways to create a Python String. We will create a string using single quotes (‘ ‘), double quotes (” “), and triple double quotes (“”” “””). The triple quotes can be used to declare multiline strings in Python.

Python
# Creating a String
# with single Quotes
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)

# Creating a String
# with double Quotes
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)

# Creating a String
# with triple Quotes
String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)

# Creating String with triple
# Quotes allows multiple lines
String1 = '''Geeks
            For
            Life'''
print("\nCreating a multiline String: ")
print(String1)

Output: 

String with the use of Single Quotes: 
Welcome to the Geeks World
String with the use of Double Quotes:
I'm a Geek
String with the use of Triple Quotes:
I'm a Geek and I live in a world of "Geeks"
Creating a multiline String:
Geeks
For
Life

Accessing characters in Python String

In Python Programming tutorials, individual characters of a String can be accessed by using the method of Indexing. Indexing allows negative address references to access characters from the back of the String, e.g. -1 refers to the last character, -2 refers to the second last character, and so on. 

While accessing an index out of the range will cause an IndexError. Only Integers are allowed to be passed as an index, float or other types that will cause a TypeError.

Python String indexing

Python String syntax indexing

Python String Positive Indexing

In this example, we will define a string in Python Programming and access its characters using positive indexing. The 0th element will be the first character of the string.

Python
String1 = "GeeksForGeeks"
print("Initial String: ", String1)

# Printing First character
print("First character of String is: ", String1[0])

Output: 

Initial String:  GeeksForGeeks
First character of String is: G

Python String Negative Indexing

In this example, we will access its characters using negative indexing. The -3th element is the third last character of the string.

Python
String1 = "GeeksForGeeks"
print("Initial String: ", String1)

# Printing Last character
print("Last character of String is: ", String1[-3])

Output

Initial String:  GeeksForGeeks
Last character of String is: e

String Slicing Python

In Python Programming tutorials, the String Slicing method is used to access a range of characters in the String. Slicing in a String is done by using a Slicing operator, i.e., a colon (:).  One thing to keep in mind while using this method is that the string returned after slicing includes the character at the start index but not the character at the last index.

In this example, we will use the string-slicing method to extract a substring of the original string. The [3:12] indicates that the string slicing will start from the 3rd index of the string to the 12th index, (12th character not including). We can also use negative indexing in string slicing.

Python
# Creating a String
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)

# Printing 3rd to 12th character
print("\nSlicing characters from 3-12: ")
print(String1[3:12])

# Printing characters between
# 3rd and 2nd last character
print("\nSlicing characters between " +
      "3rd and 2nd last character: ")
print(String1[3:-2])

Output: 

Initial String: 
GeeksForGeeks
Slicing characters from 3-12:
ksForGeek
Slicing characters between 3rd and 2nd last character:
ksForGee

Python String Reversed

In Python Programming tutorials, By accessing characters from a string, we can also reverse strings in Python Programming. We can Reverse a string by using String slicing method.

In this example, we will reverse a string by accessing the index. We did not specify the first two parts of the slice indicating that we are considering the whole string, from the start index to the last index.

Python
#Program to reverse a string
gfg = "geeksforgeeks"
print(gfg[::-1])

Output:

skeegrofskeeg

BuildIn Reverse Function in Python

We can also reverse a string by using built-in join and reversed functions, and passing the string as the parameter to the reversed() function.

Python
# Program to reverse a string

gfg = "geeksforgeeks"

# Reverse the string using reversed and join function
gfg = "".join(reversed(gfg))

print(gfg)

Output:

skeegrofskeeg

Deleting/Updating from a String

In Python, the Updation or deletion of characters from a String is not allowed. This will cause an error because item assignment or item deletion from a String is not supported. Although deletion of the entire String is possible with the use of a built-in del keyword. This is because Strings are immutable, hence elements of a String cannot be changed once assigned. Only new strings can be reassigned to the same name. 

Updating a character

A character of a string can be updated in Python by first converting the string into a Python List and then updating the element in the list. As lists are mutable in nature, we can update the character and then convert the list back into the String.

Another method is using the string slicing method. Slice the string before the character you want to update, then add the new character and finally add the other part of the string again by string slicing.

Example:

In this example, we are using both the list and the string slicing method to update a character. We converted the String1 to a list, changes its value at a particular element, and then converted it back to a string using the Python string join() method.

In the string-slicing method, we sliced the string up to the character we want to update, concatenated the new character, and finally concatenate the remaining part of the string.

Python
# Python Program to Update
# character of a String

String1 = "Hello, I'm a Geek"
print("Initial String: ")
print(String1)

# Updating a character of the String
## As python strings are immutable, they don't support item updation directly
### there are following two ways
#1
list1 = list(String1)
list1[2] = 'p'
String2 = ''.join(list1)
print("\nUpdating character at 2nd Index: ")
print(String2)

#2
String3 = String1[0:2] + 'p' + String1[3:]
print(String3)

Output: 

Initial String: 
Hello, I'm a Geek
Updating character at 2nd Index: 
Heplo, I'm a Geek
Heplo, I'm a Geek

Updating Entire String

In Python Programming, As Python strings are immutable in nature, we cannot update the existing string. We can only assign a completely new value to the variable with the same name.

Example: In this example, we first assign a value to ‘String1’ and then updated it by assigning a completely different value to it. We simply changed its reference.

Python
# Python Program to Update
# entire String

String1 = "Hello, I'm a Geek"
print("Initial String: ")
print(String1)

# Updating a String
String1 = "Welcome to the Geek World"
print("\nUpdated String: ")
print(String1)

Output: 

Initial String: 
Hello, I'm a Geek
Updated String:
Welcome to the Geek World

Deleting a character

Python strings are immutable, that means we cannot delete a character from it. When we try to delete thecharacter using the del keyword, it will generate an error.

Python
# Python Program to delete
# character of a String

String1 = "Hello, I'm a Geek"
print("Initial String: ")
print(String1)

print("Deleting character at 2nd Index: ")
del String1[2]
print(String1)

Output:

Initial String: 
Hello, I'm a Geek
Deleting character at 2nd Index:
Traceback (most recent call last):
File "e:\GFG\Python codes\Codes\demo.py", line 9, in <module>
del String1[2]
TypeError: 'str' object doesn't support item deletion

But using slicing we can remove the character from the original string and store the result in a new string.

Example: In this example, we will first slice the string up to the character that we want to delete and then concatenate the remaining string next from the deleted character.

Python
# Python Program to Delete
# characters from a String

String1 = "Hello, I'm a Geek"
print("Initial String: ")
print(String1)

# Deleting a character
# of the String
String2 = String1[0:2] + String1[3:]
print("\nDeleting character at 2nd Index: ")
print(String2)

Output: 

Initial String: 
Hello, I'm a Geek
Deleting character at 2nd Index: 
Helo, I'm a Geek

Deleting Entire String

In Python Programming, Deletion of the entire string is possible with the use of del keyword. Further, if we try to print the string, this will produce an error because the String is deleted and is unavailable to be printed.  

Python
# Python Program to Delete
# entire String

String1 = "Hello, I'm a Geek"
print("Initial String: ")
print(String1)

# Deleting a String
# with the use of del
del String1
print("\nDeleting entire String: ")
print(String1)

Error: 

Traceback (most recent call last): 
File "/home/e4b8f2170f140da99d2fe57d9d8c6a94.py", line 12, in 
print(String1) 
NameError: name 'String1' is not defined

Escape Sequencing in Python

While printing Strings with single and double quotes in it causes SyntaxError because String already contains Single and Double Quotes and hence cannot be printed with the use of either of these. Hence, to print such a String either Triple Quotes are used or Escape sequences are used to print Strings. 

Escape sequences start with a backslash and can be interpreted differently. If single quotes are used to represent a string, then all the single quotes present in the string must be escaped and the same is done for Double Quotes.

Python
# Initial String
String1 = '''I'm a "Geek"'''
print("Initial String with use of Triple Quotes: ")
print(String1)

# Escaping Single Quote
String1 = 'I\'m a "Geek"'
print("\nEscaping Single Quote: ")
print(String1)

# Escaping Double Quotes
String1 = "I'm a \"Geek\""
print("\nEscaping Double Quotes: ")
print(String1)

# Printing Paths with the
# use of Escape Sequences
String1 = "C:\\Python\\Geeks\\"
print("\nEscaping Backslashes: ")
print(String1)

# Printing Paths with the
# use of Tab
String1 = "Hi\tGeeks"
print("\nTab: ")
print(String1)

# Printing Paths with the
# use of New Line
String1 = "Python\nGeeks"
print("\nNew Line: ")
print(String1)

Output:

Initial String with use of Triple Quotes: 
I'm a "Geek"
Escaping Single Quote:
I'm a "Geek"
Escaping Double Quotes:
I'm a "Geek"
Escaping Backslashes:
C:\Python\Geeks\
Tab:
Hi Geeks
New Line:
Python
Geeks

Example:

To ignore the escape sequences in a String, r or R is used, this implies that the string is a raw string and escape sequences inside it are to be ignored.

Python
# Printing hello in octal
String1 = "\110\145\154\154\157"
print("\nPrinting in Octal with the use of Escape Sequences: ")
print(String1)

# Using raw String to
# ignore Escape Sequences
String1 = r"This is \110\145\154\154\157"
print("\nPrinting Raw String in Octal Format: ")
print(String1)

# Printing Geeks in HEX
String1 = "This is \x47\x65\x65\x6b\x73 in \x48\x45\x58"
print("\nPrinting in HEX with the use of Escape Sequences: ")
print(String1)

# Using raw String to
# ignore Escape Sequences
String1 = r"This is \x47\x65\x65\x6b\x73 in \x48\x45\x58"
print("\nPrinting Raw String in HEX Format: ")
print(String1)

Output:

Printing in Octal with the use of Escape Sequences: 
Hello
Printing Raw String in Octal Format:
This is \110\145\154\154\157
Printing in HEX with the use of Escape Sequences:
This is Geeks in HEX
Printing Raw String in HEX Format:
This is \x47\x65\x65\x6b\x73 in \x48\x45\x58

Python String Formatting

Strings in Python or string data type in Python can be formatted with the use of format() method which is a very versatile and powerful tool for formatting Strings. Format method in String contains curly braces {} as placeholders which can hold arguments according to position or keyword to specify the order.

Example 1: In this example, we will declare a string which contains the curly braces {} that acts as a placeholders and provide them values to see how string declaration position matters.

Python
# Python Program for
# Formatting of Strings

# Default order
String1 = "{} {} {}".format('Geeks', 'For', 'Life')
print("Print String in default order: ")
print(String1)

# Positional Formatting
String1 = "{1} {0} {2}".format('Geeks', 'For', 'Life')
print("\nPrint String in Positional order: ")
print(String1)

# Keyword Formatting
String1 = "{l} {f} {g}".format(g='Geeks', f='For', l='Life')
print("\nPrint String in order of Keywords: ")
print(String1)

Output: 

Print String in default order: 
Geeks For Life
Print String in Positional order:
For Geeks Life
Print String in order of Keywords:
Life For Geeks

Example 2: Integers such as Binary, hexadecimal, etc., and floats can be rounded or displayed in the exponent form with the use of format specifiers. 

Python
# Formatting of Integers
String1 = "{0:b}".format(16)
print("\nBinary representation of 16 is ")
print(String1)

# Formatting of Floats
String1 = "{0:e}".format(165.6458)
print("\nExponent representation of 165.6458 is ")
print(String1)

# Rounding off Integers
String1 = "{0:.2f}".format(1/6)
print("\none-sixth is : ")
print(String1)

Output: 

Binary representation of 16 is 
10000
Exponent representation of 165.6458 is
1.656458e+02
one-sixth is :
0.17

Example 3: In String data type in Python , A string can be left, right, or center aligned with the use of format specifiers, separated by a colon(:). The (<) indicates that the string should be aligned to the left, (>) indicates that the string should be aligned to the right and (^) indicates that the string should be aligned to the center. We can also specify the length in which it should be aligned. For example, (<10) means that the string should be aligned to the left within a field of width of 10 characters.

Python
# String alignment
String1 = "|{:<10}|{:^10}|{:>10}|".format('Geeks',
                                          'for', 
                                          'Geeks')
print("\nLeft, center and right alignment with Formatting: ")
print(String1)

# To demonstrate aligning of spaces
String1 = "\n{0:^16} was founded in {1:<4}!".format("GeeksforGeeks",
                                                    2009)
print(String1)

Output: 

Left, center and right alignment with Formatting: 
|Geeks | for | Geeks|
GeeksforGeeks was founded in 2009 !

Example 4: Old-style formatting was done without the use of the format method by using the % operator 

Python
# Python Program for
# Old Style Formatting
# of Integers

Integer1 = 12.3456789
print("Formatting in 3.2f format: ")
print('The value of Integer1 is %3.2f' % Integer1)
print("\nFormatting in 3.4f format: ")
print('The value of Integer1 is %3.4f' % Integer1)

Output: 

Formatting in 3.2f format: 
The value of Integer1 is 12.35
Formatting in 3.4f format:
The value of Integer1 is 12.3457

Similar Reads – String Methods

Useful Python String Operations  

Python String constants 

Built-In Function

Description

string.ascii_letters

Concatenation of the ascii_lowercase and ascii_uppercase constants.

string.ascii_lowercase

Concatenation of lowercase letters

string.ascii_uppercase

Concatenation of uppercase letters

string.digits

Digit in strings

string.hexdigits

Hexadigit in strings

string.letters

concatenation of the strings lowercase and uppercase

string.lowercase

A string must contain lowercase letters.

string.octdigits

Octadigit in a string

string.punctuation

ASCII characters having punctuation characters.

string.printable

String of characters which are printable

String.endswith()

Returns True if a string ends with the given suffix otherwise returns False

String.startswith()

Returns True if a string starts with the given prefix otherwise returns False

String.isdigit()

Returns “True” if all characters in the string are digits, Otherwise, It returns “False”.

String.isalpha()

Returns “True” if all characters in the string are alphabets, Otherwise, It returns “False”.

string.isdecimal()

Returns true if all characters in a string are decimal.

str.format()

one of the string formatting methods in Python3, which allows multiple substitutions and value formatting.

String.index

Returns the position of the first occurrence of substring in a string

string.uppercase

A string must contain uppercase letters.

string.whitespace

A string containing all characters that are considered whitespace.

string.swapcase()

Method converts all uppercase characters to lowercase and vice versa of the given string, and returns it

replace()

returns a copy of the string where all occurrences of a substring is replaced with another substring.

Deprecated string functions

Built-In Function

Description

string.Isdecimal

Returns true if all characters in a string are decimal

String.Isalnum

Returns true if all the characters in a given string are alphanumeric.

string.Istitle

Returns True if the string is a title cased string

String.partition

splits the string at the first occurrence of the separator and returns a tuple.

String.Isidentifier

Check whether a string is a valid identifier or not.

String.len

Returns the length of the string.

String.rindex

Returns the highest index of the substring inside the string if substring is found.

String.Max

Returns the highest alphabetical character in a string.

String.min

Returns the minimum alphabetical character in a string.

String.splitlines

Returns a list of lines in the string.

string.capitalize

Return a word with its first character capitalized.

string.expandtabs

Expand tabs in a string replacing them by one or more spaces

string.find

Return the lowest indexing a sub string.

string.rfind

find the highest index.

string.count

Return the number of (non-overlapping) occurrences of substring sub in string

string.lower

Return a copy of s, but with upper case, letters converted to lower case.

string.split

Return a list of the words of the string, If the optional second argument sep is absent or None

string.rsplit()

Return a list of the words of the string s, scanning s from the end.

rpartition()

Method splits the given string into three parts

string.splitfields

Return a list of the words of the string when only used with two arguments.

string.join

Concatenate a list or tuple of words with intervening occurrences of sep.

string.strip()

It returns a copy of the string with both leading and trailing white spaces removed

string.lstrip

Return a copy of the string with leading white spaces removed.

string.rstrip

Return a copy of the string with trailing white spaces removed.

string.swapcase

Converts lower case letters to upper case and vice versa.

string.translate

Translate the characters using table

string.upper

lower case letters converted to upper case.

string.ljust

left-justify in a field of given width.

string.rjust

Right-justify in a field of given width.

string.center()

Center-justify in a field of given width.

string-zfill

Pad a numeric string on the left with zero digits until the given width is reached.

string.replace

Return a copy of string s with all occurrences of substring old replaced by new.

string.casefold()

Returns the string in lowercase which can be used for caseless comparisons.

string.encode

Encodes the string into any encoding supported by Python. The default encoding is utf-8.

string.maketrans

Returns a translation table usable for str.translate()

Use of String in Python

  • Strings are extensively used for text processing tasks such as searching, extracting, modifying, and formatting text data.
  • Strings are used to read input from users via the standard input (stdin) or command-line arguments and to display output using print statements.
  • Strings are used to represent data in various formats, including JSON, XML, CSV, and more. They are often manipulated to extract specific information or transform data structures.
  • Strings are used to read from and write to text files. They facilitate operations such as reading the contents of a file, writing data to a file, and manipulating file paths.
  • Strings support a wide range of operations such as concatenation, slicing, indexing, searching, replacing, and splitting. These operations enable developers to manipulate and transform text efficiently.

Advantages of String in Python:

  • Strings are used at a larger scale i.e. for a wide areas of operations such as storing and manipulating text data, representing names, addresses, and other types of data that can be represented as text.
  • Python has a rich set of string methods that allow you to manipulate and work with strings in a variety of ways. These methods make it easy to perform common tasks such as converting strings to uppercase or lowercase, replacing substrings, and splitting strings into lists.
  • Strings are immutable, meaning that once you have created a string, you cannot change it. This can be beneficial in certain situations because it means that you can be confident that the value of a string will not change unexpectedly.
  • Python has built-in support for strings, which means that you do not need to import any additional libraries or modules to work with strings. This makes it easy to get started with strings and reduces the complexity of your code.
  • Python has a concise syntax for creating and manipulating strings, which makes it easy to write and read code that works with strings.

Drawbacks of String in Python:

  • When we are dealing with large text data, strings can be inefficient. For instance, if you need to perform a large number of operations on a string, such as replacing substrings or splitting the string into multiple substrings, it can be slow and consume a lot resources.
  • Strings can be difficult to work with when you need to represent complex data structures, such as lists or dictionaries. In these cases, it may be more efficient to use a different data type, such as a list or a dictionary, to represent the data.

Python String – FAQs

What is a Python string?

A Python string is a sequence of characters enclosed within quotes. It is immutable datatype, its value cannot be altered after it has been created.

How can I create a string in Python?

Strings can be created using single quotes, double quotes, or triple quotes. For Example:

Single quotes: 'Hii'
Double quotes: "Geeks"
Triple quotes: '''Welcome''' """Greeks"""

How can I access characters in a string?

Python strings are zero-indexed, so we can access single character using indexing. For Example:

String = "GeeksForGeeks"
Print(String[0]) ' Output= G '
Print(String[-1]) ' Output= s '

Can I concatenate strings in Python?

Yes, you can concatenate strings using the ‘+’ operator. For Example:

first_name = "Raja"
last_name = "Ram"
full_name = first_name + " " + last_name

How can I get the length of a string?

The length of a string can be obtained using the ‘len()’ function. For Example:

string = "GeeksForGeeks"
length = len(string)

Recent Articles on Python String 

More Videos on Python Strings

Programs of Python Strings  



Similar Reads

String slicing in Python to check if a string can become empty by recursive deletion
Given a string “str” and another string “sub_str”. We are allowed to delete “sub_str” from “str” any number of times. It is also given that the “sub_str” appears only once at a time. The task is to find if “str” can become empty by removing “sub_str” again and again. Examples: Input : str = "GEEGEEKSKS", sub_str = "GEEKS" Output : Yes Explanation :
2 min read
String slicing in Python to Rotate a String
Given a string of size n, write functions to perform following operations on string. Left (Or anticlockwise) rotate the given string by d elements (where d <= n).Right (Or clockwise) rotate the given string by d elements (where d <= n).Examples: Input : s = "GeeksforGeeks" d = 2Output : Left Rotation : "eksforGeeksGe" Right Rotation : "ksGeek
3 min read
Python | Sorting string using order defined by another string
Given two strings (of lowercase letters), a pattern and a string. The task is to sort string according to the order defined by pattern and return the reverse of it. It may be assumed that pattern has all characters of the string and all characters in pattern appear only once. Examples: Input : pat = "asbcklfdmegnot", str = "eksge" Output : str = "g
2 min read
String Alignment in Python f-string
Text Alignment in Python is useful for printing out clean formatted output. Some times the data to be printed varies in length which makes it look messy when printed. By using String Alignment the output string can be aligned by defining the alignment as left, right or center and also defining space (width) to reserve for the string. Approach : We
2 min read
String to Int and Int to String in Python
Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing the information about converting a string to int and int to string. Converting a string to an int If we want to convert a number that is represented in the string to int, we have to use the int() function. This function is used
2 min read
Pad or fill a string by a variable in Python using f-string
f-string stands for formatted string. It had come up by Python Version 3.6 and rapidly used to do easy formatting on strings. F-string is a string literal having syntax starts with f and followed by {}. That placeholder used for holding variable, that will be changed upon the variable names and their values respectively. There are already strings f
4 min read
Convert Unicode String to a Byte String in Python
Python is a versatile programming language known for its simplicity and readability. Unicode support is a crucial aspect of Python, allowing developers to handle characters from various scripts and languages. However, there are instances where you might need to convert a Unicode string to a regular string. In this article, we will explore five diff
2 min read
Python string length | len() function to find string length
The string len() function returns the length of the string. In this article, we will see how to find the length of a string using the string len() method. Example: [GFGTABS] Python string = "Geeksforgeeks" print(len(string)) [/GFGTABS]Output13String len() Syntaxlen(string) ParameterString: string of which you want to find the length. Retu
5 min read
Python String Formatting - How to format String?
String formatting allows you to create dynamic strings by combining variables and values. In this article, we will discuss about 5 ways to format a string. You will learn different methods of string formatting with examples for better understanding. Let's look at them now! How to Format Strings in PythonThere are five different ways to perform stri
10 min read
Lexicographically smallest string which is not a subsequence of given string
Given a string S, the task is to find the string which is lexicographically smallest and not a subsequence of the given string S. Examples: Input: S = "abcdefghijklmnopqrstuvwxyz"Output: aaExplanation:String "aa" is the lexicographically smallest string which is not present in the given string as a subsequence. Input: S = "aaaa"Output: aaabExplanat
5 min read
Sum of frequencies of characters of a string present in another string
Given two strings S1 and S2 of lengths M and N respectively, the task is to calculate the sum of the frequencies of the characters of string S1 in the string S2. Examples: Input: S1 = "pPKf", S2 = "KKKttsdppfP"Output: 7Explanation:The character 'p' occurs twice in the string S2.The character 'P' occurs once in the string S2.The character 'K' occurs
5 min read
Check if a string can be repeated to make another string
Given two strings a and b, the task is to check how many times the string a can be repeated to generate the string b. If b cannot be generated by repeating a then print -1. Examples: Input: a = "geeks", b = "geeksgeeks" Output: 2 "geeks" can be repeated twice to generate "geeksgeeks" Input: a = "df", b = "dfgrt" Output: -1 Recommended: Please try y
9 min read
Python String Methods | Set 1 (find, rfind, startwith, endwith, islower, isupper, lower, upper, swapcase & title)
Some of the string basics have been covered in the below articles Strings Part-1 Strings Part-2 The important string methods will be discussed in this article1. find("string", beg, end) :- This function is used to find the position of the substring within a string.It takes 3 arguments, substring , starting index( by default 0) and ending index( by
4 min read
Python String Methods | Set 2 (len, count, center, ljust, rjust, isalpha, isalnum, isspace & join)
Some of the string methods are covered in the set 3 below String Methods Part- 1 More methods are discussed in this article 1. len() :- This function returns the length of the string. 2. count("string", beg, end) :- This function counts the occurrence of mentioned substring in whole string. This function takes 3 arguments, substring, beginning posi
4 min read
Python String Methods | Set 3 (strip, lstrip, rstrip, min, max, maketrans, translate, replace & expandtabs())
Some of the string methods are covered in the below sets.String Methods Part- 1 String Methods Part- 2More methods are discussed in this article1. strip():- This method is used to delete all the leading and trailing characters mentioned in its argument.2. lstrip():- This method is used to delete all the leading characters mentioned in its argument.
4 min read
Python | String startswith()
Python String startswith() method returns True if a string starts with the specified prefix (string). If not, it returns False using Python. Python String startswith() Method SyntaxSyntax: str.startswith(prefix, start, end) Parameters: prefix: prefix ix nothing but a string that needs to be checked.start: Starting position where prefix is needed to
2 min read
Python | Pandas str.join() to join string/list elements with passed delimiter
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.join() method is used to join all elements in list present in a series with passed delimiter. Since strings are also array of
2 min read
Python String casefold() Method
Python String casefold() method is used to convert string to lowercase. It is similar to the Python lower() string method, but the case removes all the case distinctions present in a string. Python String casefold() Method Syntax Syntax: string.casefold() Parameters: The casefold() method doesn't take any parameters. Return value: Returns the case
1 min read
Reverse Words in a Given String in Python
We are given a string and we need to reverse words of a given string Examples: Input : str =" geeks quiz practice code" Output : str = code practice quiz geeks Input : str = "my name is laxmi" output : str= laxmi is name my Reverse the words in the given string program C/C++ Code # Python code # To reverse words in a given string # input string str
6 min read
Python | Check order of character in string using OrderedDict( )
Given an input string and a pattern, check if characters in the input string follows the same order as determined by characters present in the pattern. Assume there won’t be any duplicate characters in the pattern. Examples: Input: string = "engineers rock"pattern = "er";Output: trueExplanation: All 'e' in the input string are before all 'r'.Input:
3 min read
Python String isspace() Method
Python String isspace() method returns “True” if all characters in the string are whitespace characters, Otherwise, It returns “False”. This function is used to check if the argument contains all whitespace characters, such as: ‘ ‘ – Space‘\t’ – Horizontal tab‘\n’ – Newline‘\v’ – Vertical tab‘\f’ – Feed‘\r’ – Carriage returnPython String isspace()
2 min read
Python String isalpha() Method
Python String isalpha() method is used to check whether all characters in the String are an alphabet. Python String isalpha() Method SyntaxSyntax: string.isalpha() Parameters: isalpha() does not take any parameters Returns: True: If all characters in the string are alphabet.False: If the string contains 1 or more non-alphabets.Errors and Exceptions
4 min read
Python String isprintable() Method
Python String isprintable() is a built-in method used for string handling. The isprintable() method returns "True" if all characters in the string are printable or the string is empty, Otherwise, It returns "False". This function is used to check if the argument contains any printable characters such as: Digits ( 0123456789 )Uppercase letters ( ABC
3 min read
Python code to move spaces to front of string in single traversal
Given a string that has set of words and spaces, write a program to move all spaces to front of string, by traversing the string only once. Examples: Input : str = "geeks for geeks" Output : str = " geeksforgeeks" Input : str = "move these spaces to beginning" Output : str = " movethesespacestobeginning" There were four space characters in input, a
5 min read
Python String isdigit() Method
Python String isdigit() method returns “True” if all characters in the string are digits, Otherwise, It returns “False”. Python String isdigit() Method Syntax Syntax: string.isdigit() Parameters: isdigit() does not take any parameters Returns: True - If all characters in the string are digits.False - If the string contains 1 or more non-digits. Tim
3 min read
Python Regex to extract maximum numeric value from a string
Given an alphanumeric string, extract maximum numeric value from that string. Alphabets will only be in lower case. Examples: Input : 100klh564abc365bgOutput : 564Maximum numeric value among 100, 564 and 365 is 564.Input : abchsd0sdhsOutput : 0Python Regex to extract maximum numeric value from a stringThis problem has existing solution please refer
2 min read
Find all the patterns of “1(0+)1” in a given string using Python Regex
A string contains patterns of the form 1(0+)1 where (0+) represents any non-empty consecutive sequence of 0’s. Count all such patterns. The patterns are allowed to overlap. Note : It contains digits and lowercase characters only. The string is not necessarily a binary. 100201 is not a valid pattern. Examples: Input : 1101001 Output : 2 Input : 1000
2 min read
Find the first repeated word in a string in Python using Dictionary
Prerequisite : Dictionary data structure Given a string, Find the 1st repeated word in a string. Examples: Input : "Ravi had been saying that he had been there" Output : had Input : "Ravi had been saying that" Output : No Repetition Input : "he had had he" Output : he We have existing solution for this problem please refer Find the first repeated w
4 min read
Check if both halves of the string have same set of characters in Python
Given a string of lowercase characters only, the task is to check if it is possible to split a string from middle which will gives two halves having the same characters and same frequency of each character. If the length of the given string is ODD then ignore the middle element and check for the rest. Examples: Input : abbaab Output : NO The two ha
3 min read
Concatenated string with uncommon characters in Python
Two strings are given and you have to modify the 1st string such that all the common characters of the 2nd string have to be removed and the uncommon characters of the 2nd string have to be concatenated with the uncommon characters of the 1st string. Examples: Input : S1 = "aacdb", S2 = "gafd"Output : "cbgf"Input : S1 = "abcs";, S2 = "cxzca";Output
4 min read
Article Tags :
Practice Tags :