Python Examples

  • Online Python Compiler
  • Hello World
  • Console Operations
  • Conditional Statements
  • Loop Statements
  • Builtin Functions
  • Type Conversion

Collections

  • Classes and Objects
  • File Operations
  • Global Variables
  • Regular Expressions
  • Multi-threading
  • phonenumbers
  • Breadcrumbs
  • ► Python Examples
  • ► ► String Tutorials
  • ► ► ► Python String – Replace character at Specific Position
  • Python Operators
  • Python String Tutorials
  • Python String
  • Python String Operations
  • Python String Methods
  • Python - Create string
  • Python - Create string using single quotes
  • Python - Create string using double quotes
  • Python - Create string using str() builtin function
  • Python - Create multiline string
  • Python - Create empty string
  • Python - Create string of specific length
  • Python - Create string from list
  • Python - Create string from list of characters
  • Python - Create string from integer
  • Python - Create string from variable
  • Python - Create string from two variables
  • String Basics
  • Python - String length
  • Python - Substring of a string
  • Python - Slice a string
  • Python - List of strings
  • Python - Check if all strings in a list are not empty
  • Python - Print unique characters present in string
  • Python - Check if string is empty
  • Read / Print
  • Python - Read string from console
  • Python - Print String to Console Output
  • Python string - Get character at specific index
  • Python string - Get first character
  • Python string - Get last character
  • Python string - Get first n characters
  • Python string - Get last n characters
  • Python - Get substring after specific character
  • Python - Get substring before specific character
  • Python - Get substring between two specific characters
  • Python - Get substring between brackets
  • Python - Get substring from specific index to end
  • Python string - Iterate over characters
  • Python string - Iterate over words
  • Python - Check if string contains only alphabets
  • Python - Check if string contains only alphanumeric
  • Python - Check if string value is numeric
  • Python - Check if string contains substring
  • Python - Check if string contains substring from list
  • Python - Check if string contains specific character
  • Python - Check if specific character is present in string
  • Python - Check if string is an integer
  • Python - Check if string is a float value
  • Python - Check if string is a number
  • Python - Check if all strings in list are not empty
  • Python - Check if string starts with specific prefix
  • Python - Check if string ends with specific suffix
  • Replacements
  • Python - Replace substring
  • Python string - Replace multiple spaces with single space
  • Python string - Replace character at specific index
  • Python string - Replace first occurrence
  • Python string - Replace last occurrence
  • Python string - Replace first n occurrences
  • Python string - Replace from dictionary
  • Python string - Replace using regular expression
  • Python string - Replace forward slash with backward slash
  • Append/Concatenate/Insert
  • Python string - Append
  • Python string - Append a character to end
  • Python string - Append new line
  • Python string - Append number
  • Python string - Append in loop
  • Python string - Append variable
  • Python string - Append to a string variable
  • Python string - Concatenate
  • Python - Repeat string N times
  • Python string - Insert character at start
  • Python string - Insert character at specific index
  • Python - Insert string at specific position
  • Python string - Replace all occurrences
  • Python - Split string
  • Python - Split string into specific length chunks
  • Python - Split string by underscore
  • Python - Split string by space
  • Python - Split string by new line
  • Python - Split string by comma
  • Python - Split string into characters
  • Python - Split string into N equal parts
  • Python - Split string into lines
  • Python - Split string in half
  • Python - Split string by regular expression
  • Sorting Operations
  • Python - Sort List of Strings
  • Python - Sort Characters in String
  • Transformations
  • Python - Convert string to lowercase
  • Python - Convert string to uppercase
  • Python - Remove white spaces at start and end of string
  • Python - Capitalise first character of string
  • Python - Reverse string
  • Python - Center a string in specific length
  • Delete Operations
  • Python String - Remove character at specific index
  • Python String - Remove first character
  • Python String - Remove last character
  • Python String - Remove substring
  • Python String - Remove specific character
  • Python String - Remove first and last character
  • Python String - Remove first n characters
  • Python String - Remove last n characters
  • Python String - Remove first line
  • Python String - Remove spaces
  • Python String - Remove special characters
  • Conversions
  • Python - Convert string to int
  • Python - Convert string to float
  • Python - Convert string to list of characters
  • Python - Convert string to list
  • Python - Convert string to dictionary
  • Python - Convert int to string
  • Python - Convert float to string
  • Python - Convert list of characters to string
  • Python - Convert bytes to string
  • Python - Check if two strings are equal
  • Python - Check if two strings are equal ignore case
  • Python - Compare strings
  • Python strings - Compare first n characters
  • Python strings - Compare first character
  • Python strings - Compare last character
  • Python strings - Compare nth character
  • Python - Find character in first string that are not present in second string
  • Python - Find characters that are common to given strings
  • Python - Find index of substring in a string
  • Python - Find number of occurrences of substring in string
  • Python - Find number of overlapping occurrences of substring in string
  • Python - Find index of first occurrence of substring in string
  • Python - Find index of last occurrence of substring in string
  • Python - Find index of Nth occurrence of substring in string
  • Python - Find longest common prefix string
  • Python - Variables in string
  • Python - Escape single quote inside string
  • Python - Escape double quotes inside string
  • Python - Escape backslash inside string
  • Python - Write string with new line
  • Python - Print new line after variable
  • Exceptions with string data
  • Python NameError: name 'string' is not defined
  • String methods
  • Python String capitalize()
  • Python String casefold()
  • Python String center()
  • Python String count()
  • Python String endswith()
  • Python String find()
  • Python String index()
  • Python String isalnum()
  • Python String isalpha()
  • Python String isascii()
  • Python String isdecimal()
  • Python String isdigit()
  • Python String isidentifier()
  • Python String islower()
  • Python String isnumeric()
  • Python String isspace()
  • Python String istitle()
  • Python String isupper()
  • Python String join()
  • Python String lower()
  • Python String lstrip()
  • Python String maketrans()
  • Python String partition()
  • Python String removeprefix()
  • Python String removesuffix()
  • Python string replace()
  • Python String rstrip()
  • Python String split()
  • Python string splitlines()
  • Python String startswith()
  • Python String strip()
  • Python String swapcase()
  • Python String title()
  • Python String translate()
  • Python String upper()
  • Other String tutorials
  • Python - Find next character for given character in ASCII
  • Python Escape characters
  • Python - Get all possible substrings of a string
  • Python - Get k length substrings of a string
  • Python Functions

Python String – Replace character at Specific Position

  • Replace character at a given index in a string using slicing
  • Replace character at a given index in a string using list

Python – Replace Character at Specific Index in String

To replace a character with a given character at a specified index, you can use python string slicing as shown below:

where character is the new character that has to be replaced with and position is the index at which we are replacing the character.

1. Replace character at a given index in a string using slicing

In the following example, we will take a string, and replace character at index=6 with e .

Python Program

2. Replace character at a given index in a string using list

In the following example, we will take a string, and replace character at index=6 with e . To do this, we shall first convert the string to a list, then replace the item at given index with new character, and then join the list items to string.

In this tutorial of Python Examples , we learned how to replace a character at specific index in a string with a new character.

theme logo

Logical Python

Effective Python Tutorials

Python String – Indexing and Slicing

String indexing.

As a string is a collection of characters stored as an ordered sequence, each character is assigned the index position starting with 0. We can access each character by passing the index position in the square brackets.

name = ‘Peter Cruise’

Index Positions :

0 1 2 3 4 5 6 7 8 9 10 11
P e t e r space C r u i s e

Check what is at position 0.

Position 4.

String Slicing

The slicing operation can extract a substring of two or more than two characters. While performing slicing, we can pass three optional parameters in the square brackets separated by a colon.

String[ StartPosition : EndPosition : Step ]

Python String - Indexing and Slicing

When we do not use a colon, the argument is considered to be the individual character’s position.

Let us understand index positions with some examples:

Only using start to end.

Start with 3 to end.

Go up to 3. Note: Character at position 3 will not be included.

Include all with jump of 2.

Start at 2 up to 8.

Start with 1 up to 11 with jump of 3.

Negative Indexing

We can also use negative indexing. The last letter has the index position of -1. It keeps on increasing in the negative order until the first character. If we want to traverse backward, we can use step as a negative number. Example: -1.

name = ‘Peter Smith’

Negative Index Positions:

-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
P e t e r space S m i t h

Character at -2 position.

This will not work because the default jump size is 1 which is positive but to traverse backward we need a negative jump size.

Traversing from -2 uptill -6 with jump of -1.

Traversing from -5 to -2 with a positive jump i.e. default 1.

Reversing a String

We can reverse the string by using the negative indexing trick. We have to specify the step as -1.

Slice Method

The slice method in Python is a built-in function that returns a slice object, which can be used for slicing strings (and other iterable objects).

You might have already observed that it has the same parameters as we used while String slicing, i.e start, stop, step.

Default values

The slice method allows you to omit parameters. If you omit the start, stop, or step parameter, it will be considered as None . By default, if you specify only a single argument, then it is considered as the stop argument. But if you want to specify start and skip stop, then you need to use None for stop. In the same way, if you would like to specify the stop, then it is better to use None for start for more clarity.

If we have only single element, by default, it is End argument.

Start as None, means it will start from 0.

Stop as None, means it will go till last chanracter.

Both Start and Stop as None, with jump of 2.

  • Slice Object

A slice object, is used to encapsulate the start, stop and step parameters in a reusable and versatile form. The main advantage of the slice object is to re-use these parameters multiple times in the Program.

References:

  • Slicing and Indexing in Python
  • Python – Slicing Strings Examples
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

PythonForBeginners.com

PythonForBeginners.com

Learn By Example

String Indexing in Python

Author: Aditya Raj Last Updated: January 9, 2022

Strings are used for processing text data in Python. While processing strings, we often need to access a certain part of the string. In this article, we will see how we can extract parts of a string using indexing in Python. 

What is String Indexing ?

If we have an ordered sequence or container object such as a string, a list, or a tuple, we can access the elements of the objects using their relative position in the sequence. The relative position of the elements in the ordered sequence is termed as index. With Indexing, we can access any element from an ordered sequence using the indices. 

In python, string indexing is zero based. It means that we start the counting from 0 and the first character of the string is assigned the index 0, the second character is assigned the index 1, the third character is assigned the index 2 and so on. 

python string assignment by index

We can understand this using the following example.

Suppose that we have a string “PythonForBeginners”

Here, the index of the letter “P” is 0. The index of the letter “y” is 1. The index of letter ”t” is 2, The index of letter “h” is 3 and so on. The index of the last letter “s” is 17.

In python, we can use positive as well as negative numbers for string indexing. Let us discuss them one by one.

String Indexing using Positive Numbers

As we have seen above, Strings are indexed using positive numbers from 0 to string length -1. We can access a character at any position between 0 to (length of the string) -1 using positive indices as follows.

Always remember that an index greater than or equal to the string length will cause an IndexError exception as follows.

You can either avoid the IndexError exception by checking the value of index before accessing any character in the string. Alternatively, you can use python try except block to handle the exceptions if they occur.

Here, I will suggest you to use the try except blocks. Checking the index every time we access a character may be redundant and costly if we are accessing using indices less than the length of the string. While using try except blocks, the program will not check the value of index each time we access a character from the string. If IndexError occurs, it will be handled by the code in the except block. 

Indexing using Negative Numbers

We can also use negative indices for accessing characters from a string. In python, the last character of the string is assigned an index -1. The second last character is assigned an index -2. Similarly, the first character of the string is assigned an index -(length of the string).

Here, the index of the letter “s” is -1. The index of the letter “r” is -2. The index of letter ”n” is -3 , The index of letter “n” is -4 and so on. The index of the first letter “P” is -18.

You can verify this using the following program.

While using negative numbers as indices, Make sure that you do not pass an index less than  -(length of the string). Otherwise, your program will run into an IndexError as follows.

In this article, we have studied string indexing in python. We have seen how we can use negative as well as positive numbers to access characters from a string. To study more about strings in python, you can read this article on string concatenation .

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

More Python Topics

How to Replace Character in String at Index in Python

  • Python How-To's
  • How to Replace Character in String at …

Use String Slicing to Replace a Character in a String at a Certain Index in Python

Use a list to replace a character in a string at a certain index in python, replace more than one character at different indices with the same character in all the cases, replace more than one character at different indices with different characters in all the cases.

How to Replace Character in String at Index in Python

As we all know, strings in Python are immutable, so there is no possible way of directly making changes to the string during the runtime of the Python code. However, there is a need for doing this in some cases, and it can be done indirectly in different ways.

This tutorial demonstrates how to replace a character in a string at a specific index in Python.

List slicing is an efficient way to solve some of the problems encountered during the coding process. The colon ( : ) operator is utilized for the list slicing process. The details or parameters such as start , finish , and step can be specified with the help of the colon operator.

The following code uses string slicing to replace a character in a string at a certain index in Python.

The above code provides the following output:

Explanation:

  • To replace a single character at the specified position in the given string, three sections are made by splitting the given string.
  • The middle section contains only the character that needs to be replaced. The first and last sections contain the characters before and after the selected character, respectively.
  • All three sections are then joined together using the simple + operator. However, instead of the middle section containing the selected character, the character that needs to be replaced is joined in place of it.

A list is one of the four built-in datatypes that Python provides, and it is utilized to stock several items in a single variable. Lists are ordered, changeable, and have a definite count.

In this method, the given string is first converted into a list. After that, the old character is replaced by the new character at the specified index. Finally, the list items are converted to a string using the join() function.

The following code uses a List to replace a character in a string at a certain index in Python.

These two were the methods that can be utilized to deal with a single character in a string. Moving on, we will now focus on replacing characters at multiple specified indices.

Here, we will make use of Lists. This method is utilized when there are a few indices, and all the characters at these multiple indices need to be replaced by a single character.

For this to work, all the indices in the given list would need to be iterated, and slicing can be implemented for replacing each found index that requires a character change.

The following code uses list slicing for when we need to replace characters at many indices with a single character.

In this case, the same character does not need to be replaced in all the indices.

For this purpose, we will make use of a dictionary instead of a list. A dictionary is much similar to a hashmap and stores the entered data in the form of key:value pairs.

In order to replace all the characters given in the selected indices with their respective replacement, iteration all over the created dictionary’s key:value pairs.

The following code replaces characters at multiple indices with their respective replacement.

Vaibhhav Khetarpal avatar

Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.

Related Article - Python String

  • How to Remove Commas From String in Python
  • How to Check a String Is Empty in a Pythonic Way
  • How to Convert a String to Variable Name in Python
  • How to Remove Whitespace From a String in Python
  • How to Extract Numbers From a String in Python
  • How to Convert String to Datetime in Python

Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python string index() method.

❮ String Methods

Where in the text is the word "welcome"?:

Definition and Usage

The index() method finds the first occurrence of the specified value.

The index() method raises an exception if the value is not found.

The index() method is almost the same as the find() method, the only difference is that the find() method returns -1 if the value is not found. (See example below)

Parameter Values

Parameter Description
Required. The value to search for
Optional. Where to start the search. Default is 0
Optional. Where to end the search. Default is to the end of the string

More Examples

Where in the text is the first occurrence of the letter "e"?:

Where in the text is the first occurrence of the letter "e" when you only search between position 5 and 10?:

If the value is not found, the find() method returns -1, but the index() method will raise an exception:

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

  • Trending Categories

Data Structure

  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Python Program to Replace a Character at a Specific Index

In Python, we can easily replace a character at a specific index by converting the string into a list of characters using the list() method. Then, we modify the character at the desired index and convert the list back to the string using the join() method. We can also replace a character at a specific index using the slicing and replace method. In this article, we will see examples of replacing a character at a specific index in Python using list and join method, the slicing method and replace method.

Method 1: Using list() and join() method

The list() method.

The list() method takes a sequence (e.g. string, tuple, or set) as an argument and returns a list with the same elements as the sequence.

The join() method

The join() method is a string method that concatenates the elements of an iterable (e.g. list, tuple, or set) into a single string, using the specified separator string.

Suppose we have a string "Hello, World!" and we want to replace the character 'o' at index 4 with 'a'. We first convert the string to a list using the list() method. This creates a list of characters for the string “Hello, World!”. We can now access the specific character at the specified index and replace it with a new character. After replacing the character we can use the join() method to rejoin the characters in the list to form the new string.

In the below example, we replace a character at index 0 with a new character z . we define the string "hello world" and the index of the character we want to replace is 0. We also define the new character 'z'.We convert the string to a list using the list() method. Then we access the character at the specified index and replace it with the new character 'z'.

Method 2: Using Slicing Method

We use slicing to split the string into three parts: the characters before the index, the new character, and the characters after the index. Then we concatenate these parts using the + operator.

Here, the slicing method is a string method that returns a substring of the original string by specifying the starting index (inclusive), the ending index (exclusive), and the step size (optional).

In the below code, we define the string "Hello, World!", the index of the character we want to replace is 4, and the new character is 'a'. Then we use slicing to split the string into three parts: the characters before the index (string[: index]) , the new character (new_char), and the characters after the index (string[index+1:]) . Finally, we concatenate these parts using the + operator to create the new string.

Method 3: Using the replace() Method

In this method, we use the replace() method to replace the character at the specified index with the new character.

Here, the replace() method is a string method that returns a copy of the original string with all occurrences of the old_value replaced by the new_value. The count argument is optional and specifies the maximum number of occurrences to replace.

In the below code, we define the string "Hello, World!", the index of the character we want to replace is 4, and the new character is 'a'. We use slicing to split the string into two parts: the characters before the index (string[: index]) and the characters after the index (string[index:]).

Then we use the replace() method on the second part of the string (string[index:]) to replace the first occurrence of the character at the specified index with the new character (new_char). We specify the number 1 as the third argument to replace() to only replace the first occurrence.

Finally, we concatenate the two parts of the string using the + operator to create a new string.

In this article, we discussed how we can replace a character at a specific index with another character. We can simply do it by converting the string to a list of characters and then replacing the character by accessing it by its index and then rejoining the characters of the list by using the join() method. The slicing method slices the string into three parts and after replacing the character we concatenate the parts using the + operator. The replace() method can also be used to replace a character at a specific index.

Rohan Singh

  • Related Articles
  • Golang program to replace a character at a specific index
  • C++ Program to Replace a Character at a Specific Index
  • Swift Program to Replace a Character at a Specific Index
  • Java program to replace a character at a specific index
  • Python Program to Replace the Spaces of a String with a Specific Character
  • How do I replace a character at a particular index in JavaScript?
  • Java Program to Replace the Spaces of a String with a Specific Character
  • Swift Program to Replace the Spaces of a String with a Specific Character
  • Golang program to replace the spaces of string with a specific character
  • Java Program to replace one specific character with another
  • C# program to replace n-th character from a given index in a string
  • Python Pandas - Insert a new index value at a specific position
  • Java Program to get a character located at the String's specified index
  • Python program to change character of a string using given index
  • C# Program to replace a special character from a String

Kickstart Your Career

Get certified by completing the course

  • Python »
  • 3.12.6 Documentation »
  • The Python Standard Library »
  • Text Processing Services »
  • string — Common string operations
  • Theme Auto Light Dark |

string — Common string operations ¶

Source code: Lib/string.py

Text Sequence Type — str

String Methods

String constants ¶

The constants defined in this module are:

The concatenation of the ascii_lowercase and ascii_uppercase constants described below. This value is not locale-dependent.

The lowercase letters 'abcdefghijklmnopqrstuvwxyz' . This value is not locale-dependent and will not change.

The uppercase letters 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . This value is not locale-dependent and will not change.

The string '0123456789' .

The string '0123456789abcdefABCDEF' .

The string '01234567' .

String of ASCII characters which are considered punctuation characters in the C locale: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ .

String of ASCII characters which are considered printable. This is a combination of digits , ascii_letters , punctuation , and whitespace .

A string containing all ASCII characters that are considered whitespace. This includes the characters space, tab, linefeed, return, formfeed, and vertical tab.

Custom String Formatting ¶

The built-in string class provides the ability to do complex variable substitutions and value formatting via the format() method described in PEP 3101 . The Formatter class in the string module allows you to create and customize your own string formatting behaviors using the same implementation as the built-in format() method.

The Formatter class has the following public methods:

The primary API method. It takes a format string and an arbitrary set of positional and keyword arguments. It is just a wrapper that calls vformat() .

Changed in version 3.7: A format string argument is now positional-only .

This function does the actual work of formatting. It is exposed as a separate function for cases where you want to pass in a predefined dictionary of arguments, rather than unpacking and repacking the dictionary as individual arguments using the *args and **kwargs syntax. vformat() does the work of breaking up the format string into character data and replacement fields. It calls the various methods described below.

In addition, the Formatter defines a number of methods that are intended to be replaced by subclasses:

Loop over the format_string and return an iterable of tuples ( literal_text , field_name , format_spec , conversion ). This is used by vformat() to break the string into either literal text, or replacement fields.

The values in the tuple conceptually represent a span of literal text followed by a single replacement field. If there is no literal text (which can happen if two replacement fields occur consecutively), then literal_text will be a zero-length string. If there is no replacement field, then the values of field_name , format_spec and conversion will be None .

Given field_name as returned by parse() (see above), convert it to an object to be formatted. Returns a tuple (obj, used_key). The default version takes strings of the form defined in PEP 3101 , such as “0[name]” or “label.title”. args and kwargs are as passed in to vformat() . The return value used_key has the same meaning as the key parameter to get_value() .

Retrieve a given field value. The key argument will be either an integer or a string. If it is an integer, it represents the index of the positional argument in args ; if it is a string, then it represents a named argument in kwargs .

The args parameter is set to the list of positional arguments to vformat() , and the kwargs parameter is set to the dictionary of keyword arguments.

For compound field names, these functions are only called for the first component of the field name; subsequent components are handled through normal attribute and indexing operations.

So for example, the field expression ‘0.name’ would cause get_value() to be called with a key argument of 0. The name attribute will be looked up after get_value() returns by calling the built-in getattr() function.

If the index or keyword refers to an item that does not exist, then an IndexError or KeyError should be raised.

Implement checking for unused arguments if desired. The arguments to this function is the set of all argument keys that were actually referred to in the format string (integers for positional arguments, and strings for named arguments), and a reference to the args and kwargs that was passed to vformat. The set of unused args can be calculated from these parameters. check_unused_args() is assumed to raise an exception if the check fails.

format_field() simply calls the global format() built-in. The method is provided so that subclasses can override it.

Converts the value (returned by get_field() ) given a conversion type (as in the tuple returned by the parse() method). The default version understands ‘s’ (str), ‘r’ (repr) and ‘a’ (ascii) conversion types.

Format String Syntax ¶

The str.format() method and the Formatter class share the same syntax for format strings (although in the case of Formatter , subclasses can define their own format string syntax). The syntax is related to that of formatted string literals , but it is less sophisticated and, in particular, does not support arbitrary expressions.

Format strings contain “replacement fields” surrounded by curly braces {} . Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }} .

The grammar for a replacement field is as follows:

In less formal terms, the replacement field can start with a field_name that specifies the object whose value is to be formatted and inserted into the output instead of the replacement field. The field_name is optionally followed by a conversion field, which is preceded by an exclamation point '!' , and a format_spec , which is preceded by a colon ':' . These specify a non-default format for the replacement value.

See also the Format Specification Mini-Language section.

The field_name itself begins with an arg_name that is either a number or a keyword. If it’s a number, it refers to a positional argument, and if it’s a keyword, it refers to a named keyword argument. An arg_name is treated as a number if a call to str.isdecimal() on the string would return true. If the numerical arg_names in a format string are 0, 1, 2, … in sequence, they can all be omitted (not just some) and the numbers 0, 1, 2, … will be automatically inserted in that order. Because arg_name is not quote-delimited, it is not possible to specify arbitrary dictionary keys (e.g., the strings '10' or ':-]' ) within a format string. The arg_name can be followed by any number of index or attribute expressions. An expression of the form '.name' selects the named attribute using getattr() , while an expression of the form '[index]' does an index lookup using __getitem__() .

Changed in version 3.1: The positional argument specifiers can be omitted for str.format() , so '{} {}'.format(a, b) is equivalent to '{0} {1}'.format(a, b) .

Changed in version 3.4: The positional argument specifiers can be omitted for Formatter .

Some simple format string examples:

The conversion field causes a type coercion before formatting. Normally, the job of formatting a value is done by the __format__() method of the value itself. However, in some cases it is desirable to force a type to be formatted as a string, overriding its own definition of formatting. By converting the value to a string before calling __format__() , the normal formatting logic is bypassed.

Three conversion flags are currently supported: '!s' which calls str() on the value, '!r' which calls repr() and '!a' which calls ascii() .

Some examples:

The format_spec field contains a specification of how the value should be presented, including such details as field width, alignment, padding, decimal precision and so on. Each value type can define its own “formatting mini-language” or interpretation of the format_spec .

Most built-in types support a common formatting mini-language, which is described in the next section.

A format_spec field can also include nested replacement fields within it. These nested replacement fields may contain a field name, conversion flag and format specification, but deeper nesting is not allowed. The replacement fields within the format_spec are substituted before the format_spec string is interpreted. This allows the formatting of a value to be dynamically specified.

See the Format examples section for some examples.

Format Specification Mini-Language ¶

“Format specifications” are used within replacement fields contained within a format string to define how individual values are presented (see Format String Syntax and f-strings ). They can also be passed directly to the built-in format() function. Each formattable type may define how the format specification is to be interpreted.

Most built-in types implement the following options for format specifications, although some of the formatting options are only supported by the numeric types.

A general convention is that an empty format specification produces the same result as if you had called str() on the value. A non-empty format specification typically modifies the result.

The general form of a standard format specifier is:

If a valid align value is specified, it can be preceded by a fill character that can be any character and defaults to a space if omitted. It is not possible to use a literal curly brace (” { ” or “ } ”) as the fill character in a formatted string literal or when using the str.format() method. However, it is possible to insert a curly brace with a nested replacement field. This limitation doesn’t affect the format() function.

The meaning of the various alignment options is as follows:

Option

Meaning

Forces the field to be left-aligned within the available space (this is the default for most objects).

Forces the field to be right-aligned within the available space (this is the default for numbers).

Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types. It becomes the default for numbers when ‘0’ immediately precedes the field width.

Forces the field to be centered within the available space.

Note that unless a minimum field width is defined, the field width will always be the same size as the data to fill it, so that the alignment option has no meaning in this case.

The sign option is only valid for number types, and can be one of the following:

Option

Meaning

indicates that a sign should be used for both positive as well as negative numbers.

indicates that a sign should be used only for negative numbers (this is the default behavior).

space

indicates that a leading space should be used on positive numbers, and a minus sign on negative numbers.

The 'z' option coerces negative zero floating-point values to positive zero after rounding to the format precision. This option is only valid for floating-point presentation types.

Changed in version 3.11: Added the 'z' option (see also PEP 682 ).

The '#' option causes the “alternate form” to be used for the conversion. The alternate form is defined differently for different types. This option is only valid for integer, float and complex types. For integers, when binary, octal, or hexadecimal output is used, this option adds the respective prefix '0b' , '0o' , '0x' , or '0X' to the output value. For float and complex the alternate form causes the result of the conversion to always contain a decimal-point character, even if no digits follow it. Normally, a decimal-point character appears in the result of these conversions only if a digit follows it. In addition, for 'g' and 'G' conversions, trailing zeros are not removed from the result.

The ',' option signals the use of a comma for a thousands separator. For a locale aware separator, use the 'n' integer presentation type instead.

Changed in version 3.1: Added the ',' option (see also PEP 378 ).

The '_' option signals the use of an underscore for a thousands separator for floating-point presentation types and for integer presentation type 'd' . For integer presentation types 'b' , 'o' , 'x' , and 'X' , underscores will be inserted every 4 digits. For other presentation types, specifying this option is an error.

Changed in version 3.6: Added the '_' option (see also PEP 515 ).

width is a decimal integer defining the minimum total field width, including any prefixes, separators, and other formatting characters. If not specified, then the field width will be determined by the content.

When no explicit alignment is given, preceding the width field by a zero ( '0' ) character enables sign-aware zero-padding for numeric types. This is equivalent to a fill character of '0' with an alignment type of '=' .

Changed in version 3.10: Preceding the width field by '0' no longer affects the default alignment for strings.

The precision is a decimal integer indicating how many digits should be displayed after the decimal point for presentation types 'f' and 'F' , or before and after the decimal point for presentation types 'g' or 'G' . For string presentation types the field indicates the maximum field size - in other words, how many characters will be used from the field content. The precision is not allowed for integer presentation types.

Finally, the type determines how the data should be presented.

The available string presentation types are:

Type Meaning 's' String format. This is the default type for strings and may be omitted. None The same as 's' .

The available integer presentation types are:

Type Meaning 'b' Binary format. Outputs the number in base 2. 'c' Character. Converts the integer to the corresponding unicode character before printing. 'd' Decimal Integer. Outputs the number in base 10. 'o' Octal format. Outputs the number in base 8. 'x' Hex format. Outputs the number in base 16, using lower-case letters for the digits above 9. 'X' Hex format. Outputs the number in base 16, using upper-case letters for the digits above 9. In case '#' is specified, the prefix '0x' will be upper-cased to '0X' as well. 'n' Number. This is the same as 'd' , except that it uses the current locale setting to insert the appropriate number separator characters. None The same as 'd' .

In addition to the above presentation types, integers can be formatted with the floating-point presentation types listed below (except 'n' and None ). When doing so, float() is used to convert the integer to a floating-point number before formatting.

The available presentation types for float and Decimal values are:

Type Meaning 'e' Scientific notation. For a given precision p , formats the number in scientific notation with the letter ‘e’ separating the coefficient from the exponent. The coefficient has one digit before and p digits after the decimal point, for a total of p + 1 significant digits. With no precision given, uses a precision of 6 digits after the decimal point for float , and shows all coefficient digits for Decimal . If no digits follow the decimal point, the decimal point is also removed unless the # option is used. 'E' Scientific notation. Same as 'e' except it uses an upper case ‘E’ as the separator character. 'f' Fixed-point notation. For a given precision p , formats the number as a decimal number with exactly p digits following the decimal point. With no precision given, uses a precision of 6 digits after the decimal point for float , and uses a precision large enough to show all coefficient digits for Decimal . If no digits follow the decimal point, the decimal point is also removed unless the # option is used. 'F' Fixed-point notation. Same as 'f' , but converts nan to NAN and inf to INF . 'g' General format. For a given precision p >= 1 , this rounds the number to p significant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude. A precision of 0 is treated as equivalent to a precision of 1 . The precise rules are as follows: suppose that the result formatted with presentation type 'e' and precision p-1 would have exponent exp . Then, if m <= exp < p , where m is -4 for floats and -6 for Decimals , the number is formatted with presentation type 'f' and precision p-1-exp . Otherwise, the number is formatted with presentation type 'e' and precision p-1 . In both cases insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it, unless the '#' option is used. With no precision given, uses a precision of 6 significant digits for float . For Decimal , the coefficient of the result is formed from the coefficient digits of the value; scientific notation is used for values smaller than 1e-6 in absolute value and values where the place value of the least significant digit is larger than 1, and fixed-point notation is used otherwise. Positive and negative infinity, positive and negative zero, and nans, are formatted as inf , -inf , 0 , -0 and nan respectively, regardless of the precision. 'G' General format. Same as 'g' except switches to 'E' if the number gets too large. The representations of infinity and NaN are uppercased, too. 'n' Number. This is the same as 'g' , except that it uses the current locale setting to insert the appropriate number separator characters. '%' Percentage. Multiplies the number by 100 and displays in fixed ( 'f' ) format, followed by a percent sign. None For float this is the same as 'g' , except that when fixed-point notation is used to format the result, it always includes at least one digit past the decimal point. The precision used is as large as needed to represent the given value faithfully. For Decimal , this is the same as either 'g' or 'G' depending on the value of context.capitals for the current decimal context. The overall effect is to match the output of str() as altered by the other format modifiers.

Format examples ¶

This section contains examples of the str.format() syntax and comparison with the old % -formatting.

In most of the cases the syntax is similar to the old % -formatting, with the addition of the {} and with : used instead of % . For example, '%03.2f' can be translated to '{:03.2f}' .

The new format syntax also supports new and different options, shown in the following examples.

Accessing arguments by position:

Accessing arguments by name:

Accessing arguments’ attributes:

Accessing arguments’ items:

Replacing %s and %r :

Aligning the text and specifying a width:

Replacing %+f , %-f , and % f and specifying a sign:

Replacing %x and %o and converting the value to different bases:

Using the comma as a thousands separator:

Expressing a percentage:

Using type-specific formatting:

Nesting arguments and more complex examples:

Template strings ¶

Template strings provide simpler string substitutions as described in PEP 292 . A primary use case for template strings is for internationalization (i18n) since in that context, the simpler syntax and functionality makes it easier to translate than other built-in string formatting facilities in Python. As an example of a library built on template strings for i18n, see the flufl.i18n package.

Template strings support $ -based substitutions, using the following rules:

$$ is an escape; it is replaced with a single $ .

$identifier names a substitution placeholder matching a mapping key of "identifier" . By default, "identifier" is restricted to any case-insensitive ASCII alphanumeric string (including underscores) that starts with an underscore or ASCII letter. The first non-identifier character after the $ character terminates this placeholder specification.

${identifier} is equivalent to $identifier . It is required when valid identifier characters follow the placeholder but are not part of the placeholder, such as "${noun}ification" .

Any other appearance of $ in the string will result in a ValueError being raised.

The string module provides a Template class that implements these rules. The methods of Template are:

The constructor takes a single argument which is the template string.

Performs the template substitution, returning a new string. mapping is any dictionary-like object with keys that match the placeholders in the template. Alternatively, you can provide keyword arguments, where the keywords are the placeholders. When both mapping and kwds are given and there are duplicates, the placeholders from kwds take precedence.

Like substitute() , except that if placeholders are missing from mapping and kwds , instead of raising a KeyError exception, the original placeholder will appear in the resulting string intact. Also, unlike with substitute() , any other appearances of the $ will simply return $ instead of raising ValueError .

While other exceptions may still occur, this method is called “safe” because it always tries to return a usable string instead of raising an exception. In another sense, safe_substitute() may be anything other than safe, since it will silently ignore malformed templates containing dangling delimiters, unmatched braces, or placeholders that are not valid Python identifiers.

Returns false if the template has invalid placeholders that will cause substitute() to raise ValueError .

Added in version 3.11.

Returns a list of the valid identifiers in the template, in the order they first appear, ignoring any invalid identifiers.

Template instances also provide one public data attribute:

This is the object passed to the constructor’s template argument. In general, you shouldn’t change it, but read-only access is not enforced.

Here is an example of how to use a Template:

Advanced usage: you can derive subclasses of Template to customize the placeholder syntax, delimiter character, or the entire regular expression used to parse template strings. To do this, you can override these class attributes:

delimiter – This is the literal string describing a placeholder introducing delimiter. The default value is $ . Note that this should not be a regular expression, as the implementation will call re.escape() on this string as needed. Note further that you cannot change the delimiter after class creation (i.e. a different delimiter must be set in the subclass’s class namespace).

idpattern – This is the regular expression describing the pattern for non-braced placeholders. The default value is the regular expression (?a:[_a-z][_a-z0-9]*) . If this is given and braceidpattern is None this pattern will also apply to braced placeholders.

Since default flags is re.IGNORECASE , pattern [a-z] can match with some non-ASCII characters. That’s why we use the local a flag here.

Changed in version 3.7: braceidpattern can be used to define separate patterns used inside and outside the braces.

braceidpattern – This is like idpattern but describes the pattern for braced placeholders. Defaults to None which means to fall back to idpattern (i.e. the same pattern is used both inside and outside braces). If given, this allows you to define different patterns for braced and unbraced placeholders.

Added in version 3.7.

flags – The regular expression flags that will be applied when compiling the regular expression used for recognizing substitutions. The default value is re.IGNORECASE . Note that re.VERBOSE will always be added to the flags, so custom idpattern s must follow conventions for verbose regular expressions.

Added in version 3.2.

Alternatively, you can provide the entire regular expression pattern by overriding the class attribute pattern . If you do this, the value must be a regular expression object with four named capturing groups. The capturing groups correspond to the rules given above, along with the invalid placeholder rule:

escaped – This group matches the escape sequence, e.g. $$ , in the default pattern.

named – This group matches the unbraced placeholder name; it should not include the delimiter in capturing group.

braced – This group matches the brace enclosed placeholder name; it should not include either the delimiter or braces in the capturing group.

invalid – This group matches any other delimiter pattern (usually a single delimiter), and it should appear last in the regular expression.

The methods on this class will raise ValueError if the pattern matches the template without one of these named groups matching.

Helper functions ¶

Split the argument into words using str.split() , capitalize each word using str.capitalize() , and join the capitalized words using str.join() . If the optional second argument sep is absent or None , runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise sep is used to split and join the words.

Table of Contents

  • String constants
  • Custom String Formatting
  • Format Specification Mini-Language
  • Format examples
  • Template strings
  • Helper functions

Previous topic

Text Processing Services

re — Regular expression operations

  • Report a Bug
  • Show Source

Strings and Character Data in Python

Strings and Character Data in Python

Table of Contents

Getting to Know Strings and Characters in Python

Standard string literals, escape sequences in string literals, raw string literals, formatted string literals, the built-in str() function, concatenating strings: the + operator, repeating strings: the * operator, finding substrings in a string: the in and not in operators, finding the number of characters: len(), converting objects into strings: str() and repr(), formatting strings: format(), processing characters through code points: ord() and chr(), indexing strings, slicing strings, using f-strings, using the .format() method.

  • Using the Modulo Operator (%)

Manipulating Casing

Finding and replacing substrings, classifying strings, formatting strings, joining and splitting strings.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Strings and Character Data in Python

In Python, string objects contain sequences of characters that allow you to manipulate textual data. It’s rare to find an application, program, or library that doesn’t need to manipulate strings to some extent. So, processing characters and strings is integral to programming and a fundamental skill for you as a Python programmer.

In this tutorial, you’ll learn how to:

  • Create strings using literals and the str() function
  • Use operators and built-in functions with strings
  • Index and slice strings
  • Do string interpolation and formatting
  • Use string methods

To get the most out of this tutorial, you should have a good understanding of core Python concepts, including variables , functions , and operators and expressions .

Get Your Code: Click here to download the free sample code that shows you how to work with strings and character data in Python.

Take the Quiz: Test your knowledge with our interactive “Python Strings and Character Data” quiz. You’ll receive a score upon completion to help you track your learning progress:

Interactive Quiz

This quiz will test your understanding of Python's string data type and your knowledge about manipulating textual data with string objects. You'll cover the basics of creating strings using literals and the str() function, applying string methods, using operators and built-in functions, and more!

Python provides the built-in string ( str ) data type to handle textual data. Other programming languages, such as Java , have a character data type for single characters. Python doesn’t have that. Single characters are strings of length one.

In practice, strings are immutable sequences of characters. This means you can’t change a string once you define it. Any operation that modifies a string will create a new string instead of modifying the original one.

A string is also a sequence , which means that the characters in a string have a consecutive order. This feature allows you to access characters using integer indices that start with 0 . You’ll learn more about these concepts in the section about indexing strings . For now, you’ll learn about how to create strings in Python.

Creating Strings in Python

There are different ways to create strings in Python. The most common practice is to use string literals . Because strings are everywhere and have many use cases, you’ll find a few different types of string literals. There are standard literals, raw literals, and formatted literals.

Additionally, you can use the built-in str() function to create new strings from other existing objects.

In the following sections, you’ll learn about the multiple ways to create strings in Python and when to use each of them.

A standard string literal is just a piece of text or a sequence of characters that you enclose in quotes. To create single-line strings, you can use single ( '' ) and double ( "" ) quotes:

In the first example, you use single quotes to delimit the string literal. In the second example, you use double quotes.

Note: Python’s standard REPL displays string objects using single quotes even though you create them using double quotes.

You can define empty strings using quotes without placing characters between them:

An empty string doesn’t contain any characters, so when you use the built-in len() function with an empty string as an argument, you get 0 as a result.

To create multiline strings, you can use triple-quoted strings. In this case, you can use either single or double quotes:

The primary use case for triple-quoted strings is to create multiline strings. You can also use them to define single-line strings, but this is a less common practice.

Probably the most common use case for triple-quoted strings is when you need to provide docstrings for your packages, modules , functions , classes , and methods .

If you want to include a quote character within the string, then you can delimit that string with another type of quote. For example, if a string contains a single quote character, then you can delimit it with double quotes, and vice versa:

In the first example, your string includes a single quote as part of the text. To delimit the literal, you use double quotes. In the second example, you do the opposite.

Sometimes, you want Python to interpret a character or sequence of characters within a string differently. This may occur in one of two ways. You may want to:

  • Apply special meaning to characters
  • Suppress special character meaning

To achieve these goals, you can use a backslash ( \ ) character combined with other characters. The combination of a backslash and a specific character is called an escape sequence . That’s because the backslash causes the subsequent character to escape its usual meaning.

For example, you can escape a single quote character using the \' escape sequence in a string delimited by single quotes:

In this example, the backslash escapes the single quote character by suppressing its usual meaning, which is delimiting string literals. Now, Python knows that your intention isn’t to terminate the string but to embed the single quote.

The following table shows sequences that escape the default meaning of characters in string literals:

Character Usual Interpretation Escape Sequence Escaped Interpretation
Delimits a string literal Literal single quote ( ) character
Delimits a string literal Literal double quote ( ) character
Terminates the input line Newline is ignored
Introduces an escape sequence Literal backslash ( ) character

You already have an idea of how the first two escape sequences work. Now, how does the newline escape sequence work? Usually, a newline character terminates a physical line of input. To add a newline character, you just press Enter in the middle of a string. This will raise a SyntaxError exception:

When you press Enter after typing "Hello , you get a SyntaxError . If you need to break up a string over more than one line, then you can include a backslash before each newline or before pressing the Enter key:

When you add a backslash before you press Enter , Python ignores the newline and interprets the whole construct as a single physical line.

Sometimes, you need to include a literal backslash character in a string. If that backslash doesn’t precede a character with a special meaning, then you can insert it right away:

In this example, the character after the backslash doesn’t match any known escape sequence, so Python inserts the actual backslash for you. Note how the resulting string automatically doubles the backslash. Even though this example works, the best practice is to always double the backslash when you need this character in a string.

However, you may have the need to include a backslash right before a character that makes up an escape sequence:

Because the sequence \" matches a known escape sequence, your string fails with a SyntaxError . To avoid this issue, you can double the backslash:

In this update, you double the backslash to escape the character and prevent Python from raising an error.

Note: When you use the built-in print() function to print a string that includes an escaped backslash, then you won’t see the double backslash in the output:

In this example, the output only displays one backslash, producing the desired effect.

Up to this point, you’ve learned how to suppress the meaning of a given character by escaping it. Suppose you need to create a string containing a tab character. Some text editors may allow you to insert a tab character directly into your code. However, this is considered a poor practice for several reasons:

  • Computers can distinguish between tabs and a sequence of spaces, but human beings can’t because these characters are visually indistinguishable.
  • Some text editors automatically eliminate tabs by expanding them to an appropriate number of spaces.
  • Some Python REPL environments won’t insert tabs into code.

In Python, you can specify a tab character with the \t escape sequence:

The \t escape sequence changes the usual meaning of the letter t , making Python interpret the combination as a tab character.

Here’s a list of escape sequences that cause Python to apply special meaning to some characters instead of interpreting them literally:

Escape Sequence Escaped Interpretation
ASCII Bell ( ) character
ASCII Backspace ( ) character
ASCII Formfeed ( ) character
ASCII Linefeed ( ) character
Character from Unicode database with given
ASCII Carriage return ( ) character
ASCII Horizontal tab ( ) character
Unicode character with 16-bit hex value
Unicode character with 32-bit hex value
ASCII Vertical tab ( ) character
Character with octal value
Character with hex value

The newline or linefeed character ( \n ) is probably the most popular of these escape sequences. This sequence is commonly used to create nicely formatted text outputs that span multiple lines.

Here are a few examples of the escape sequences in action:

These escape sequences are useful when you need to insert characters that aren’t readily generated from the keyboard or aren’t easily readable or printable.

With raw string literals, you can create strings that don’t translate escape sequences. Any backslash characters are left in the string.

Note: To learn more about raw strings, check out the What Are Python Raw Strings? tutorial.

To create a raw string, you have to prepend the string literal with the letter r or R :

The raw string suppresses the meaning of the escape sequence, such as \t , and presents the characters as they are.

Raw strings are commonly used to create regular expressions because they allow you to use several different characters that may have special meanings without restrictions.

Note: To learn more about regular expressions in Python, check out the tutorials on regular expressions in Python Part 1 and Part 2 .

For example, say that you want to create a regular expression to match email addresses. To do this, you can use a raw string to create the regular expression like in the code below:

The pattern variable holds a raw string that makes up a regular expression to match email addresses. Note how the string contains several backslashes that are escaped and inserted into the resulting string as they are. Then, you compile the regular expression and check for matches in a sample piece of text.

Formatted string literals, or f-strings for short, allow you to interpolate values into your strings and format them as you need.

To create a string with an f-string literal, you must prepend the literal with an f or F letter. F-strings let you interpolate values into replacement fields in your string literal. You create these fields using curly brackets.

Here’s a quick example of an f-string literal:

In this example, you interpolate the name variable into your string using an f-string literal and a replacement field.

You’ll learn more about using f-strings for string interpolation and formatting in the Doing String Interpolation and Formatting section.

You can create new strings using the built-in str() function. However, a more common use case for this function is to convert other data types into strings, which is also a way to create new strings.

Consider the following examples:

In the first example, you call the str() function without an argument to create an empty string. Then, you use the function to convert objects from different built-in types into strings.

Using Operators on Strings

You can also use a few operators with string values as operands. For example, the + and * operators allow you to perform string concatenation and repetition , respectively. In the following sections, you’ll learn how these and other operators work with strings.

The + operator lets you concatenate strings . So, in this context, you can call it the concatenation operator . Concatenation involves joining two or more string objects to create a single new string:

In this example, you use the plus operator to concatenate several string objects. You start with the greeting variable and add a comma followed by a space. Next, you add the name variable and finally, some exclamation points. Note that you’ve combined variables holding strings and string literals to build the final string.

Note: Often you’d use f-strings instead of + to concatenate strings.

The concatenation operator also has an augmented variation denoted by += . This operator allows you to do something like string = string + another_string but in a shorter way:

In this example, you create a filename incrementally. You start with the filename without the file extension. Then, you use the augmented concatenation operator to add the file extension to the existing filename.

Note that the augmented operator doesn’t change the initial string because strings are immutable. Instead, it creates a new string and reassigns it to the name file .

The * operator allows you to repeat a given string a certain number of times. In this context, this operator is known as the repetition operator . Its syntax is shown below:

The repetition operator takes two operands. One operand is the string that you want to repeat, while the other operand is an integer number representing the number of times you want to repeat the target string:

In the first example, you repeat the = character ten times. In the second example, you repeat the text Hi! ten times as well. Note that the order of the operands doesn’t affect the result.

The multiplier operand, n , is usually a positive integer. If it’s a zero or negative integer, the result is an empty string:

You need to be aware of this behavior in situations where you compute n dynamically, and 0 or negative values can occur. Otherwise, this operator comes in handy when you need to present some output to your users in a table format.

For example, say that you have the following data about your company’s employees:

You want to create a function that takes this data, puts it into a table, and prints it to the screen. In this situation, you can write a function like the following:

This function takes the employees’ data as an argument and the headers for the table. Then, it gets the maximum header length, prints the headers using the pipe character ( | ) as a separator, and justifies the headers to the left.

To separate the headers from the table’s content, you build a line of hyphens. To create the line, you use the repetition operator with the maximum header length as the multiplier operand. The effect of using the operator here is that you’ll get a visual line under each header that’s always as long as the longest header field. Finally, you print the employees’ data.

Here’s how the function works in practice:

Again, creating tables like this one is a great use case for the repetition operator because it allows you to create separators dynamically.

The repetition operator also has an augmented variation that lets you do something like string = string * n in a shorter way:

In this example, the *= operator repeats the string in sep ten times and assigns the result back to the sep variable.

Python also provides the in and not in operators that you can use with strings. The in operator returns True if the left-hand operand is contained within the right-hand one and False otherwise. This type of check is known as a membership test.

You can take advantage of a membership test when you need to determine if a substring appears in a given string:

In these examples, you check whether the string "food" is a substring of the strings on the right-hand side.

Note: To learn more about how to find substrings in existing strings, check out the How to Check if a Python String Contains a Substring tutorial.

The not in operator does the opposite check:

With the not in operator, you can check if a substring isn’t found in a given string. If the substring isn’t in the target string, then you get True . Otherwise, you get False .

Exploring Built-in Functions for String Processing

Python provides many functions that are built into the language and, therefore, are always available to you. Here are a few of these functions that are especially useful when you’re processing strings:

Function Description
Returns the length of a string
Returns a user-friendly string representation of an object
Returns a developer-friendly string representation of an object
Allows for string formatting
Converts a character to an integer
Converts an integer to a character

In the following sections, you’ll learn how to use these functions to work with your strings. To kick things off, you’ll start by determining the length of an existing string with len() .

A common operation that you’ll perform on strings is determining their number of characters. To complete this task, you can use the built-in len() function.

Note: To learn more about the len() function, check out the Using the len() Function in Python tutorial.

With a string as an argument, the len() function returns the length of the input string or the number of characters in that string. Here are a couple of examples of how to use len() :

The word "Python" has six letters, so calling len() with this word as an argument returns 6 . Note that len() returns 0 when you call it with empty strings. The function calculates the number of characters in a string object, independent of how you constructed the string:

You use the \N escape sequence to define a string with a single snake emoji. Even though you wrote nine characters in the string literal, the string object consist of a single 🐍 character. And len() reports its length as one. You get the same result when you create the string with a literal emoji character.

To convert objects into their string representation, you can use the built-in str() and repr() functions. With the str() function, you can convert a given object into its user-friendly representation . This type of string representation is targeted at end users.

For example, if you pass an object of a built-in type to str() , then you get a representation that typically consists of a string containing the literal that defines the object at hand:

In these examples, the outputs show user-friendly representations of the input objects. These representations coincide with the objects’ literals.

You can provide a user-friendly string representation for your custom classes through the .__str__() special method, as you’ll learn in a moment.

Similarly, the built-in repr() function gives you a developer-friendly representation of the object at hand:

Ideally, you should be able to copy the output of repr() to re-create the original object. Also, this representation lets you know how the object is built. It’s because of these two distinctions that you can say repr() returns a developer-friendly string representation of the object at hand.

As you can see in the example above, the output of str() and repr() is the same for built-in data types. Both functions return the object’s literal as a string.

Note: Behind the str() function, you have the .__str__() special method . Similarly, behind repr() , you have the .__repr__() method. To learn more about these special methods, check out the When Should You Use .__repr__() vs .__str__() in Python? tutorial.

To see the difference between str() and repr() , consider the Person class in the following example:

The .__repr__() method gives you a developer-friendly string representation of specific Person objects. You’ll be able to re-create the object using the output of the repr() function. In contrast, the string representation that you get from calling .__str__() should aim to be readable and informative for end users. You can access this representation with the str() function.

Here’s how the two functions work with an instance of your class:

In this example, you can use the output of repr() to re-create the object stored in john . You also have all the information about how this specific object was built. Meanwhile, the output of str() gives you no clue about how to build the object. However, it does provide useful information for the end user.

You can use the built-in format() function to format strings. This function converts an input value into a formatted representation. To define the desired format, you can use a format specifier, which should be a string that follows the syntax defined in the string formatting mini-language.

Note: To learn more about format specifiers, check out the Python’s Format Mini-Language for Tidy Strings tutorial.

Consider the following examples of using the format() function with different input values and format specifiers:

In these examples, the ".4f" specifier formats the input value as a floating-point number with four decimal places.

With the ",.2f" format specifier, you can format a number using commas as thousand separators and with two decimal places, which could be appropriate for formatting currency values.

Next, you use the "=^30" specifier to format the string "Header" centered in a width of 30 characters using the equal sign as a filler character. Finally, you use "%a %b %d, %Y" to format the date.

The ord() function returns an integer value representing the Unicode code point for the given character.

At the most basic level, computers store all information as numbers . To represent character data, computers use a translation scheme that maps each character to its associated number, which is its code point.

The most commonly used scheme is ASCII , which covers the familiar Latin characters you’re probably most accustomed to working with. For these characters, ord() returns the ASCII value that corresponds to the character at hand:

While the ASCII character set is fine for representing English, many natural languages are used worldwide, and countless symbols and glyphs appear in digital media. The complete set of characters that you may need to represent in code surpasses the Latin letters, numbers, and symbols.

Unicode is a generally accepted standard that attempts to provide a numeric code for every possible character in every possible natural language on every platform or operating system. The Unicode character set is the standard in Python.

Note: For more information about Unicode in Python, check out the Unicode & Character Encodings in Python: A Painless Guide tutorial and Python’s Unicode Support in the Python documentation.

The ord() function will return numeric values for Unicode characters as well:

In the Unicode table, the "€" character has 8364 as its associated code point, and the "∑" character has the 8721 code point.

The chr() function does the reverse of ord() . It returns the character value associated with a given code point:

Given the numeric value n , chr(n) returns the character that corresponds to n . Note that chr() handles Unicode characters as well.

Indexing and Slicing Strings

Python’s strings are ordered sequences of characters. Because of this, you can access individual characters from a string using the characters’ associated index . What’s a character’s index? Each character in a string has an index that specifies its position. Indices are integer numbers that start at 0 and go up to the number of characters in the string minus one.

You can use these indices to perform two common operations:

  • Indexing : Consists of retrieving a given character using its associated index.
  • Slicing : Allows you to get a portion of an existing string using indices.

In the following sections, you’ll learn how to run these two operations on your Python strings.

You can access individual characters in a string by specifying the string object followed by the character’s index in square brackets ( [] ). This operation is known as indexing .

String indexing in Python is zero-based, which means that the first character in the string has an index of 0 , the next has an index of 1 , and so on. The index of the last character will be the length of the string minus one.

For example, a schematic diagram of the indices of the string "foobar" would look like this:

String index 1

You can access individual characters by their index:

Using the indexing operator [index] , you can access individual characters in an existing string. Note that attempting to index beyond the end of the string results in an error:

When you use an index that’s beyond the number of characters in the string minus one, you get an IndexError exception.

You can also use negative numbers as indices. If you do that, then the indexing occurs from the end of the string backward. Index -1 refers to the last character, index -2 refers to the second-last character, and so on.

Here’s the diagram showing both positive and negative indices in the string "foobar" :

String index 2

Here are some examples of negative indexing:

With negative indices, you can access the characters from the end of the string to its beginning. Again, attempting to index with negative numbers beyond the beginning of the string results in an error:

Because the "foobar" string only has six characters, the last negative index that you can use is -6 , which corresponds to the first character in the string.

In short, for any non-empty string, s[len(s) - 1] and s[-1] both return the last character. Similarly, s[0] and s[-len(s)] return the first character. Note that no index makes sense on an empty string.

Finally, you should keep in mind that because strings are immutable, you can’t perform index assignments on them. The following example illustrates this fact:

If you try to change a character in an existing string, then you’ll get a TypeError telling you that strings don’t support item assignment .

Python allows you to extract substrings from a string. This operation is known as slicing . If s is a string, then an expression of the form s[m:n] returns the portion of s starting at index m , and up to but not including index n :

The first index sets the starting point of the indexing operation. The second index specifies the first character that isn’t included in the result—the character "r" with index 5 in the example above.

Note: String indices are zero-based. This means that the first character in a string has an index of 0 . This applies to both standard indexing and slicing.

If you omit the first index, then the slicing starts at the beginning of the string:

Therefore, slicings like s[:m] and s[0:m] are equivalent. Similarly, if you omit the second index as in s[n:] , then the slicing extends from the first index to the end of the string. This is an excellent and concise alternative to the more cumbersome s[n:len(s)] syntax:

When you omit the last index, the slicing operation extends up to the end of the string.

For any string s and any integer n , provided that n ≥ 0 , you’ll have s[:n] + s[n:] is equal to s :

The first slicing extracts the characters from the beginning and up to index 4 , which isn’t included. The second slicing extracts the characters from 4 to the end of the string. So, the result will contain the same characters as the original string.

Omitting both indices returns the original string in its entirety. It doesn’t return a copy but a reference to the original string:

When you omit both indices, you tell Python that you want to extract a slice containing the whole string. Again, for efficiency reasons, Python returns a reference instead of a copy of the original string. You can confirm this behavior using the built-in id() function.

If the first index in a slicing is greater than or equal to the second index, then Python returns an empty string:

As you can see, this behavior provides a somewhat obfuscated way to generate empty strings.

You can also use negative indices in slicing. Just as with indexing, -1 refers to the last character, -2 to the second-last character, and so on. The diagram below shows how to slice the substring "oob" from the string "foobar" using both positive and negative indices:

String index 3

Here’s the corresponding Python code:

Slicing with negative indices really shines when you need to get slices that have the last character of the string as a reference point.

There’s one more variant of the slicing syntax to discuss. An additional colon ( : ) and a third index designate a stride, also known as a step. This index indicates how many characters to jump after retrieving each character in the slice.

For example, for the string "foobar" , the slice [0:6:2] starts with the first character and ends with the last character, skipping every second character. This behavior is shown in the following diagram, where the green items are the ones included in the slice:

String stride 1

Similarly, [1:6:2] specifies a slice that starts with the second character, which is index 1 , and ends with the last character. Again, the stride value 2 skips every other character:

String stride 2

The illustrative REPL code is shown below:

As with any slicing, the first and second indices can be omitted and default to the first and last characters, respectively:

In the first slicing, you omit the first and second indices, making the slice start at index 0 and go up to the end of the string. In the second slicing, you only omit the second index, and the slice goes up to the end of the string.

You can also specify a negative stride value, in which case Python steps backward through the string. Note that the initial index should be greater than the ending index:

In the above example, [5:0:-2] means this: start at the last character and step backward by 2 , up to but not including the first character.

When you step backward, if the first and second indices are omitted, the defaults are reversed intuitively. In other words, the initial index defaults to the end of the string, and the ending index defaults to the beginning.

Here’s an example:

Using a step equal to -1 provides a common technique for reversing strings:

To dive deeper into how to reverse strings, check out the Reverse Strings in Python: reversed() , Slicing, and More tutorial.

Doing String Interpolation and Formatting

String interpolation refers to building new strings by inserting values into a string that works as a template with replacement fields for each value you insert. String formatting , on the other hand, involves applying a desired format to the values you insert in a given string through interpolation.

Note: To dive deeper into string interpolation, check out the String Interpolation in Python: Exploring Available Tools tutorial.

Similarly, if you want to learn more about string formatting, check out the Python String Formatting: Available Tools and Their Features tutorial.

In the following sections, you’ll learn the basics of string interpolation and formatting in Python.

You can also use f-strings to interpolate values into a string and format them, as you quickly touched on in the section about f-string literals . To do this, you use format specifiers that use the syntax defined in Python’s string format mini-language. For example, here’s how you can present numeric values using a currency format:

Inside the replacement field delimited by the curly brackets, you have the variable you want to interpolate and the format specifier, which is the string that starts with a colon ( : ). In this example, the format specifier defines a floating-point number with two decimal places.

Note: To learn more about using f-strings for string interpolation and formatting, check out the Python’s F-String for String Interpolation and Formatting tutorial.

F-strings have a clean syntax and are quite popular in Python code. However, they’re only suitable for those situations where you want to do the interpolation eagerly because the interpolated values are inserted when Python executes the strings.

You can’t use f-strings for lazy interpolation. In other words, you can’t use f-string for those situations where you need a reusable template that you’ll fill with values dynamically in different parts of your code. In this situation, you can use the str.format() method.

Python’s str class has a method called .format() that allows for string interpolation and formatting. This method is pretty powerful. Like f-strings, it supports the string formatting mini-language, but unlike f-strings, it allows for both eager and lazy string interpolation.

Consider the following example that uses .format() to create a balance report:

In this example, you first define two variables to hold the debit and credit of a bank account. Then, you create a template to construct a report showing the account’s credit, debit, and balance. Finally, you call .format() with the required argument to create the report.

Using the Modulo Operator ( % )

Python has another tool you can use for string interpolation and formatting called the modulo operator ( % ). This operator was the first tool Python provided for string interpolation and formatting. It also allows you to do both eager and lazy interpolation.

Note: To learn more about the modulo operator for string formatting and interpolation, check out the Modulo String Formatting in Python tutorial.

While you can use the modulo operator for string formatting, its formatting capabilities are limited and it doesn’t support the string formatting mini-language.

Here’s how you would use the modulo operator to code the example from the previous section:

In this version of the report template, you use named placeholders with the modulo operator syntax. To provide the values to interpolate, you use a dictionary. The operator unpacks it using the keys that match the replacement fields.

Exploring str Class Methods

Methods are functions that you define inside classes. Like a function, you call a method to perform a specific task. Unlike a function, you invoke a method on a specific object or class so it has knowledge of its containing object during execution.

The syntax for invoking a method on an object is shown below:

object.method([arg_0, arg_2, ..., arg_n]) class.method([arg_0, arg_2, ..., arg_n])

This invokes method .method() on object object . Inside the parentheses, you can specify the arguments for the method to work, but these arguments are optional. Note that you can have both instance and class methods .

Note: In the above syntax, the arguments specified in square brackets ( [] ) are optional and the brackets aren’t part of the syntax. You’ll use this same convention throughout the following sections.

Python’s str class provides a rich set of methods that you can use to format your strings in several different ways. In the next section, you’ll learn the basics of some of the more commonly used str methods.

The str methods you’ll look at in this section allow you to perform case conversion on the target string. Note that the methods in this section only affect letters. Non-letter characters remain the same because they don’t have uppercase and lowercase variations.

Note: Keep in mind that because strings are immutable, when string methods apply changes to an existing string they return a new string object.

To kick things off, you’ll start by capitalizing some strings using the .capitalize() method.

.capitalize()

The .capitalize() method returns a copy of the target string with its first character converted to uppercase, and all other characters converted to lowercase:

In this example, only the first letter in the target string is converted to uppercase. The rest of the letters are converted to lowercase.

The .lower() method returns a copy of the target string with all alphabetic characters converted to lowercase:

You can see in this example how all the uppercase letters were converted to lowercase.

.swapcase()

The .swapcase() method returns a copy of the target string with uppercase alphabetic characters converted to lowercase and vice versa:

In this example, the call to .swapcase() turned the lowercase letters into uppercase and the uppercase letters into lowercase.

The .title() method returns a copy of the target string in which the first letter of each word is converted to uppercase, and the remaining letters are lowercase:

Note that this method doesn’t attempt to distinguish between important and unimportant words, and it doesn’t handle apostrophes, possessives, or acronyms gracefully:

The .title() method converts the first letter of each word in the target string to uppercase. As you can see, it doesn’t do a great job with apostrophes and acronyms!

The .upper() method returns a copy of the target string with all alphabetic characters converted to uppercase:

By calling .upper() on a string, you get a new string with all the letters in uppercase.

The methods in this section provide various ways to search the target string for a specified substring.

Each method supports optional start and end arguments. These arguments mean that the action of the method is restricted to the portion of the target string starting with the character at index start and up to but not including the character at index end . If start is specified but end isn’t, then the method applies to the portion of the target string from start through the end of the string.

.count(sub[, start[, end]])

The .count(sub) method returns the number of non-overlapping occurrences of the substring sub in the target string:

The count is restricted to the number of occurrences within the substring indicated by start and end if you specify them:

In this example, the search starts at index 0 and ends at index 8 . Because of this, the last occurrence of "oo" isn’t counted.

.find(sub[, start[, end]])

You can use .find() to check whether a string contains a particular substring. Calling .find(sub) returns the lowest index in the target string where sub is found:

Note that .find() returns -1 if the specified substring isn’t found in the target string:

Again, the search is restricted to the substring indicated by start and end if you specify them:

With the start and end indices, you restrict the search to a portion of the target string.

.index(sub[, start[, end]])

The .index() method is similar to .find() , except that it raises an exception rather than returning -1 if sub isn’t found in the target string:

If the substring exists in the target string, then .index() returns the index at which the first instance of the substring starts. If the substring isn’t found in the target string, then you get a ValueError exception.

.rfind(sub[, start[, end]])

The .rfind(sub) call returns the highest index in the target string where the substring sub is found:

As with .find() , if the substring isn’t found, then .rfind() returns -1 :

You can restrict the search to the substring indicated by start and end :

Again, with the start and end indices, you restrict the search to a portion of the target string.

.rindex(sub[, start[, end]])

The .rindex() method is similar to .rfind() , except that it raises an exception if sub isn’t found in the target string:

If the substring isn’t found in the target string, then rindex() raises a ValueError exception.

.startswith(prefix[, start[, end]])

The .startswith(prefix) call returns True if the target string starts with the specified prefix and False otherwise:

The comparison is restricted to the substring indicated by start and end if they’re specified:

In these examples, you use the start and end indices to restrict the search to a given portion of the target string.

.endswith(suffix[, start[, end]])

The .endswith(suffix) call returns True if the target string ends with the specified suffix and False otherwise:

The comparison is restricted to the substring indicated by start and end if you specify them.

The methods in this section classify a string based on its characters. In all cases, the methods are predicates , meaning they return True or False depending on the condition they check.

The .isalnum() method returns True if the target string isn’t empty and all its characters are alphanumeric, meaning either a letter or number. Otherwise, it returns False :

In the first example, you get True because the target string contains only letters and numbers. In the second example, you get False because of the "$" character.

The .isalpha() method returns True if the target string isn’t empty and all its characters are alphabetic. Otherwise, it returns False :

The .isalpha() method allows you to check whether all the characters in a given string are letters. Note that whitespaces aren’t considered alpha characters, which makes sense but might be missed if you’re working with normal text.

You can use the .isdigit() method to check whether your string is made of only digits:

The .isdigit() method returns True if the target string is not empty and all its characters are numeric digits. Otherwise, it returns False .

.isidentifier()

The .isidentifier() method returns True if the target string is a valid Python identifier according to the language definition. Otherwise, it returns False :

It’s important to note that .isidentifier() will return True for a string that matches a Python keyword even though that wouldn’t be a valid identifier:

You can test whether a string matches a Python keyword using a function called iskeyword() , which is contained in a module called keyword . One possible way to do this is shown below:

If you want to ensure that a string serves as a valid Python identifier, you should check that .isidentifier() returns True and that iskeyword() returns False .

The .islower() method returns True if the target string isn’t empty and all its alphabetic characters are lowercase. Otherwise, it returns False :

Note that non-alphabetic characters are ignored when you call the .islower() method on a given string.

.isprintable()

The .isprintable() method returns True if the target string is empty or if all its alphabetic characters are printable:

You get False if the target string contains at least one non-printable character. Again, non-alphabetic characters are ignored.

Note that .isprintable() is one of two .is*() methods that return True if the target string is empty. The second one is .isascii() .

The .isspace() method returns True if the target string isn’t empty and all its characters are whitespaces. Otherwise, it returns False .

The most commonly used whitespace characters are space ( " " ), tab ( "\t" ), and newline ( "\n" ):

There are a few other ASCII characters that qualify as whitespace characters, and if you account for Unicode characters, there are quite a few beyond that:

The "\f" and "\r" combinations are the escape sequences for the ASCII form feed and carriage return characters. The "\u2005" combination is the escape sequence for the Unicode four-per-em space.

The .istitle() method returns True if the target string isn’t empty, the first alphabetic character of each word is uppercase, and all other alphabetic characters in each word are lowercase. It returns False otherwise:

This method returns True if the string is title-cased as would result from calling .title() . It returns False otherwise.

The .isupper() method returns True if the target string isn’t empty and all its alphabetic characters are uppercase. Otherwise, it returns False :

Again, Python ignores non-alphabetic characters when you call the .isupper() method on a given string object.

The methods in this section allow you to modify or enhance the format of a string in many different ways. You’ll start by learning how to center your string within a given space.

.center(width[, fill])

The .center(width) call returns a string consisting of the target string centered in a field of width characters. By default, padding consists of the ASCII space character:

If you specify the optional fill argument, then it’s used as the padding character:

Note that if the target string is as long as width or longer, then it’s returned unchanged.

.expandtabs(tabsize=8)

The .expandtabs() method replaces each tab character ( "\t" ) found in the target string with spaces. By default, spaces are filled in assuming eight characters per tab:

In the final example, you use the tabsize argument, which is an optional argument that specifies an alternate tab size.

.ljust(width[, fill])

The .ljust(width) call returns a string consisting of the target string left-justified in a field of width characters. By default, the padding consists of the ASCII space character:

If the target string is as long as width or longer, then it’s returned unchanged.

.rjust(width[, fill])

The .rjust(width) call returns a string consisting of the target string right-justified in a field of width characters. By default, the padding consists of the ASCII space character:

If the target string is as long as width or longer, then it’s returned unchanged:

When the target string is as long as width or longer, then .rjust() won’t have space to justify the text, so you get the original string back.

.removeprefix(prefix)

The .removeprefix() method returns a copy of the target string with prefix removed from the beginning:

The prefix is removed if the target string begins with that exact substring. If the original string doesn’t begin with prefix , then the string is returned unchanged.

.removesuffix(suffix)

The .removesuffix() method returns a copy of the target string with suffix removed from the end:

The suffix is removed if the target string ends with that exact substring. If the original string doesn’t end with suffix , then the string is returned unchanged. The .removeprefix() and .removesuffix() methods were introduced in Python 3.9 .

.lstrip([chars])

The .lstrip() method returns a copy of the target string with any whitespace characters removed from the left end:

If you specify the optional chars argument, then it’s a string that specifies the set of characters to be removed:

In this example, you remove the http:// prefix from the input URL using the .lstrip() method with the "/:htp" characters as an argument.

Note that this call to .lstrip() works only because the URL doesn’t start with any of the target characters:

In this example, the result isn’t correct because the URL starts with a p , which is included in the set of letters that you want to remove. You should use .removeprefix() instead.

.rstrip([chars])

The .rstrip() method with no arguments returns a copy of the target string with any whitespace characters removed from the right end:

If you specify the optional chars argument, then it should be a string that specifies the set of characters to be removed:

By providing a string value to chars , you can control the set of characters to remove from the right side of the target string.

.strip([chars])

The .strip() method is equivalent to invoking .lstrip() and .rstrip() in succession. Without the chars argument, it removes leading and trailing whitespace in one go:

As with .lstrip() and .rstrip() , the optional chars argument specifies the set of characters to be removed:

Again, with chars , you can control the characters you want to remove from the original string, which defaults to whitespaces.

.replace(old, new[, count])

To replace a substring of a string, you can use the .replace() method. This method returns a copy of the target string with all the occurrences of the old substring replaced by new :

If you specify the optional count argument, then a maximum of count replacements are performed, starting at the left end of the target string:

The count argument lets you specify how many replacements you want to perform in the original string.

.zfill(width)

The .zfill(width) call returns a copy of the target string left-padded with zeroes to the specified width :

If the target string contains a leading sign, then it remains at the left edge of the result string after zeros are inserted:

Python will still zero-pad a string that isn’t a numeric value:

The .zfill() method is useful for representing numeric values. However, it also works with textual strings.

The methods you’ll explore in this section allow you to convert between a string and some composite data types by joining objects together to make a string or by breaking a string up into pieces.

These methods operate on or return iterables , which are collections of objects. For example, many of these methods return a list or a tuple .

.join(iterable)

The .join() method takes an iterable of string objects and returns the string that results from concatenating the objects in the input iterable separated by the target string.

Note: To learn more about string concatenation, check out the Splitting, Concatenating, and Joining Strings tutorial.

Note that .join() is invoked on a string that works as the separator between each item in the input iterable, which must contain string objects.

In the following example, the separator is a string consisting of a comma and a space. The input iterable is a list of string values:

The result of this call to .join() is a single string consisting of string objects separated by commas.

Again, the input iterable must contain string objects. Otherwise, you’ll get an error:

This example fails because the second object in the input iterable isn’t a string object but an integer number.

When you have iterables of values that aren’t strings, then you can use the str() function to convert them before passing them to .join() . Consider the following example:

In this example, you use the str() function to convert the values in numbers to strings before feeding them to .join() . To do the conversion, you use a generator expression .

.partition(sep)

The .partition(sep) call splits the target string at the first occurrence of string sep . The return value is a tuple with three objects:

  • The portion of the target string that precedes sep
  • The sep object itself
  • The portion of the target string that follows sep

Here are a couple of examples of .partition() in action:

Note that if the string ends with the target sep , then the last item in the tuple is an empty string. Similarly, if sep isn’t found in the target string, then the returned tuple contains the string followed by two empty strings, as you see in the final example.

.rpartition(sep)

The .rpartition(sep) call works like .partition(sep) , except that the target string is split at the last occurrence of sep instead of the first:

In this case, the string partition is done starting from the right side of the target string.

.split(sep=None, maxsplit=-1)

Without arguments, .split() splits the target string into substrings delimited by any sequence of whitespace and returns the substrings as a list:

If you specify the sep argument, then it’s used as the delimiter for the splitting:

When sep is explicitly given as a delimiter, consecutive instances of the delimiter in the target string are assumed to delimit empty strings:

However, consecutive whitespace characters are combined into a single delimiter, and the resulting list will never contain empty strings:

If the optional parameter maxsplit is specified, then a maximum of that many splits are performed, starting from the left end of the target string:

In this example, .split() performs only one split, starting from the left end of the target string.

.rsplit(sep=None, maxsplit=-1)

The .rsplit() method behaves like .split() , except that if maxsplit is specified, then the splits are counted from the right end of the target string rather than from the left end:

If maxsplit isn’t specified, then the results of .split() and .rsplit() are indistinguishable.

.splitlines([keepends])

The .splitlines() method splits the target string into lines and returns them in a list. The following escape sequences can work as line boundaries:

Sequence Description
Newline
Carriage return
Carriage return + line feed
or Line tabulation
or Form feed
File separator
Group separator
Record separator
Next line (C1 control code)
Unicode line separator
Unicode paragraph separator

Here’s an example of using several different line separators:

If consecutive line boundary characters are present in the target string, then they’re assumed to delimit blank lines, which will appear in the result list as empty strings:

Note that if you set the optional keepends argument to True , then the line boundaries are retained in the result strings.

You now know about Python’s many tools for string creation and manipulation, including string literals, operators, and built-in functions. You’ve also learned how to extract items and parts of existing strings using the indexing and slicing operators. Finally, you’ve looked at the methods the str class provides for string formatting and processing.

In this tutorial, you’ve learned how to:

  • Use operators and built-in functions with string objects
  • Extract characters and portions of a string through indexing and slicing
  • Interpolate and format values into your strings
  • Use various string methods

With this knowledge, you’re ready to start creating and processing textual data in your Python code. You can always come back to this tutorial if you ever need a quick reference on how to use string methods.

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Leodanis Pozo Ramos

Leodanis Pozo Ramos

Leodanis is an industrial engineer who loves Python and software development. He's a self-taught Python developer with 6+ years of experience. He's an avid technical writer with a growing number of articles published on Real Python and other sites.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren Santos

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!

Keep Learning

Related Topics: basics python

Recommended Video Course: Strings and Character Data in Python

Related Tutorials:

  • Functional Programming in Python: When and How to Use It
  • Lists vs Tuples in Python
  • Python's F-String for String Interpolation and Formatting
  • Python Classes: The Power of Object-Oriented Programming
  • Asynchronous Iterators and Iterables in Python

Keep reading Real Python by creating a free account or signing in:

Already have an account? Sign-In

Almost there! Complete this form and click the button below to gain instant access:

Strings and Character Data in Python (Sample Code)

🔒 No spam. We take your privacy seriously.

python string assignment by index

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, python introduction.

  • Get Started With Python

Your First Python Program

  • Python Comments

Python Fundamentals

  • Python Variables and Literals
  • Python Type Conversion
  • Python Basic Input and Output
  • Python Operators

Python Flow Control

  • Python if...else Statement
  • Python for Loop
  • Python while Loop
  • Python break and continue
  • Python pass Statement

Python Data types

  • Python Numbers and Mathematics
  • Python List
  • Python Tuple
  • Python String
  • Python Dictionary
  • Python Functions
  • Python Function Arguments

Python Variable Scope

  • Python Global Keyword
  • Python Recursion
  • Python Modules
  • Python Package
  • Python Main function

Python Files

  • Python Directory and Files Management
  • Python CSV: Read and Write CSV files
  • Reading CSV files in Python
  • Writing CSV files in Python
  • Python Exception Handling
  • Python Exceptions
  • Python Custom Exceptions

Python Object & Class

  • Python Objects and Classes
  • Python Inheritance
  • Python Multiple Inheritance
  • Polymorphism in Python
  • Python Operator Overloading

Python Advanced Topics

  • List comprehension
  • Python Lambda/Anonymous Function
  • Python Iterators
  • Python Generators
  • Python Namespace and Scope
  • Python Closures
  • Python Decorators
  • Python @property decorator
  • Python RegEx

Python Date and Time

  • Python datetime
  • Python strftime()
  • Python strptime()
  • How to get current date and time in Python?
  • Python Get Current Time
  • Python timestamp to datetime and vice-versa
  • Python time Module
  • Python sleep()

Additional Topic

  • Precedence and Associativity of Operators in Python
  • Python Keywords and Identifiers
  • Python Asserts
  • Python Json
  • Python *args and **kwargs

Python Tutorials

Python Data Types

Python String strip()

  • Python String isalnum()
  • Python String lower()

Python Strings

In Python, a string is a sequence of characters. For example, "hello" is a string containing a sequence of characters 'h' , 'e' , 'l' , 'l' , and 'o' .

We use single quotes or double quotes to represent a string in Python. For example,

Here, we have created a string variable named string1 . The variable is initialized with the string "Python Programming" .

  • Example: Python String

In the above example, we have created string-type variables: name and message with values "Python" and "I love Python" respectively.

Here, we have used double quotes to represent strings, but we can use single quotes too.

  • Access String Characters in Python

We can access the characters in a string in three ways.

  • Indexing : One way is to treat strings as a list and use index values. For example,
  • Negative Indexing : Similar to a list, Python allows negative indexing for its strings. For example,
  • Slicing : Access a range of characters in a string by using the slicing operator colon : . For example,

Note : If we try to access an index out of the range or use numbers other than an integer, we will get errors.

  • Python Strings are Immutable

In Python, strings are immutable. That means the characters of a string cannot be changed. For example,

However, we can assign the variable name to a new string. For example,

  • Python Multiline String

We can also create a multiline string in Python. For this, we use triple double quotes """ or triple single quotes ''' . For example,

In the above example, anything inside the enclosing triple quotes is one multiline string.

  • Python String Operations

Many operations can be performed with strings, which makes it one of the most used data types in Python.

1. Compare Two Strings

We use the == operator to compare two strings. If two strings are equal, the operator returns True . Otherwise, it returns False . For example,

In the above example,

  • str1 and str2 are not equal. Hence, the result is False .
  • str1 and str3 are equal. Hence, the result is True .

2. Join Two or More Strings

In Python, we can join (concatenate) two or more strings using the + operator.

In the above example, we have used the + operator to join two strings: greet and name .

  • Iterate Through a Python String

We can iterate through a string using a for loop . For example,

  • Python String Length

In Python, we use the len() method to find the length of a string. For example,

  • String Membership Test

We can test if a substring exists within a string or not, using the keyword in .

  • Methods of Python String

Besides those mentioned above, there are various string methods present in Python. Here are some of those methods:

Methods Description
Converts the string to uppercase
Converts the string to lowercase
Returns a tuple
Replaces substring inside
Returns the index of the first occurrence of substring
Removes trailing characters
Splits string from left
Checks if string starts with the specified string
Checks numeric characters
Returns index of substring
  • Escape Sequences in Python

The escape sequence is used to escape some of the characters present inside a string.

Suppose we need to include both a double quote and a single quote inside a string,

Since strings are represented by single or double quotes, the compiler will treat "He said, " as a string. Hence, the above code will cause an error.

To solve this issue, we use the escape character \ in Python.

Here is a list of all the escape sequences supported by Python.

Escape Sequence Description
Backslash
Single quote
Double quote
ASCII Bell
ASCII Backspace
ASCII Formfeed
ASCII Linefeed
ASCII Carriage Return
ASCII Horizontal Tab
ASCII Vertical Tab
Character with octal value ooo
Character with hexadecimal value HH
  • Python String Formatting (f-Strings)

Python f-Strings makes it easy to print values and variables. For example,

Here, f'{name} is from {country}' is an f-string .

This new formatting syntax is powerful and easy to use. From now on, we will use f-Strings to print strings and variables.

  • Python str()
  • Python String Interpolation

Table of Contents

Before we wrap up, let’s put your knowledge of Python string to the test! Can you solve the following challenge?

Write a function to double every letter in a string.

  • For input 'hello' , the return value should be 'hheelllloo' .

Video: Python Strings

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

Python Tutorial

Python Library

BalaPriyaC's avatar

The .index() string method searches through a string variable for the occurrence of a pattern or a substring.

If the substring is not found, a ValueError will be raised.

In the above syntax for the .index() method:

  • pattern (Required): The pattern or substring to search for.
  • start (Optional): The starting index of string to search. The default is 0.
  • end (Optional): The index of the slice of string to search up to, non-inclusive. The default is end of the string.

Use .index() method to search for the occurrence of 'Python' in the string variable my_string :

The starting index of the substring 'Python' is 9.

Use .index() method to search for the occurrence of 'Coding' in the string variable my_string :

There will be an error:

Codebyte Example

Use .index() method to search for the occurrence of 'code' in a slice of the string variable my_string (i.e. from the character at index 8 up to, but not including, the character at index 16):

All contributors

Anonymous contributor's avatar

Contribute to Docs

  • Learn more about how to get involved.
  • Edit this page on GitHub to fix an error or make an improvement.
  • Submit feedback to let us know how we can improve Docs.

Learn Python on Codecademy

Computer science, learn python 3.

  • Python Course
  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Python String

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.

Table of Content

What is a String in Python?

Create a string in python, accessing characters in python string, string slicing python, python string reversed, deleting/updating from a string, escape sequencing in python, python string formatting.

  • Useful Python String Operations  

Python String constants 

Deprecated string functions.

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

Example of string data type 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.

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.

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 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.

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.

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.

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.

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.

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.

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.

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.

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.

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.  

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.

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.

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.

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. 

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.

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

Similar Reads – String Methods

Useful Python String Operations   

  • Logical Operators on String
  • String Formatting using %
  • String Template Class
  • Split a string
  • Python Docstrings
  • String slicing
  • Find all duplicate characters in string
  • Reverse string in Python (5 different ways)
  • Python program to check if a string is palindrome or not

Built-In Function

Description

Concatenation of the ascii_lowercase and ascii_uppercase constants.

Concatenation of lowercase letters

Concatenation of uppercase letters

Digit in strings

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

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

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

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

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

Returns true if all characters in a string are decimal.

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

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

string.uppercase

A string must contain uppercase letters.

A string containing all characters that are considered whitespace.

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

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

Built-In Function

Description

Returns true if all characters in a string are decimal

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

Returns True if the string is a title cased string

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

Check whether a string is a valid identifier or not.

Returns the length of the string.

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

Returns the highest alphabetical character in a string.

Returns the minimum alphabetical character in a string.

Returns a list of lines in the string.

Return a word with its first character capitalized.

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

Return the lowest indexing a sub string.

find the highest index.

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

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

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

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

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.

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

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

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

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

Converts lower case letters to upper case and vice versa.

Translate the characters using table

lower case letters converted to upper case.

left-justify in a field of given width.

Right-justify in a field of given width.

Center-justify in a field of given width.

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

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

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

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

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

  • Python String Methods – Part1
  • Python String Methods – Part2  
  • Python String Methods – Part 3  
  • Logical Operations and Splitting in Strings  

Programs of Python Strings   

  • Strings – Set 1 , Set 2
  • String Methods – Set 1 , Set 2 , Set 3
  • Regular Expressions (Search, Match and Find All)
  • Python String Title method
  • Swap commas and dots in a String
  • Program to convert String to a List
  • Count and display vowels in a string
  • Python program to check the validity of a Password
  • Python program to count number of vowels using sets in given string
  • Check for URL in a String
  • Check if a Substring is Present in a Given String
  • Check if two strings are anagram or not
  • Map function and Dictionary in Python to sum ASCII values
  • Map function and Lambda expression in Python to replace characters
  • SequenceMatcher in Python for Longest Common Substring
  • Print the initials of a name with last name in full
  • The k most frequent words from data set in Python
  • Find all close matches of input string from a list
  • Check if there are K consecutive 1’s in a binary number
  • Lambda and filter in Python
  • Concatenated string with uncommon characters in Python
  • Check if both halves of the string have same set of characters in Python
  • Find the first repeated word in a string in Python
  • Second most repeated word in a sequence in Python
  • K’th Non-repeating Character in Python 
  • Reverse words in a given String in Python
  • Print number with commas as 1000 separators in Python
  • Prefix matching in Python using pytrie module
  • Python Regex to extract maximum numeric value from a string
  • Pairs of complete strings in two sets
  • Remove all duplicates words from a given sentence
  • Sort words of sentence in ascending order
  • Reverse each word in a sentence
  • Python code to print common characters of two Strings in alphabetical order
  • Python program to split and join a string
  • Python code to move spaces to front of string in single traversal
  • Run Length Encoding in Python
  • Remove all duplicates from a given string in Python
  • Ways to increment a character in Python
  • Execute a String of Code in Python
  • String slicing in Python to check if a string can become empty by recursive deletion
  • Ways to print escape characters in Python
  • String slicing in Python to rotate a string
  • Count occurrences of a word in string
  • Find the k most frequent words from data set in Python
  • Python | Print the initials of a name with last name in full
  • Zip function in Python to change to a new character set
  • Python String isnumeric() and its application
  • Sort the words in lexicographical order in Python
  • Find the Number Occurring Odd Number of Times using Lambda expression and reduce function
  • Convert a list of characters into a string
  • Python groupby method to remove all consecutive duplicates
  • Python program for removing i-th character from a string
  • Replacing strings with numbers in Python for Data Analysis
  • Formatted string literals (f-strings) in Python
  • Permutation of a given string using inbuilt function
  • Find frequency of each word in a string in Python
  • Program to accept the strings which contains all vowels
  • Count the Number of matching characters in a pair of string
  • Count all prefixes in given string with greatest frequency
  • Program to check if a string contains any special character
  • Generating random strings until a given string is generated
  • Python program to count upper and lower case characters without using inbuilt functions

Please Login to comment...

Similar reads.

  • python-string
  • How to Strikethrough on Discord
  • Discord Launches End-To-End Encryption For Audio & Video Chats
  • iPadOS 18 is Now Available: Complete Features and How to Install
  • Microsoft’s Latest 365 Copilot Updates: Enhanced AI Tools for Excel, PowerPoint, and Teams
  • 10 Best PrimeWire Alternatives (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Assign new values to each index of a string

I am trying to assign some values to the characters:

My function called sumassign(s) asks for the user to input the above characters and I should return the sum of the above characters, the expected output is shown below

My codes are below.

When I try to use my code, it returns 0 instead of the sum

dmitryro's user avatar

2 Answers 2

This is what data structures like dictionaries are for. If you want to map a character to a value, the most common was to do it is with a dict. If you do that, everything else gets much easier. For example:

It's worth spending time to at least have a basic understanding of lists and dictionaries before going too much further. They are essential to writing idiomatic Python.

Mark's user avatar

You can separate the characters and the numbers into arrays and use a for loop to iterate through every number in the numbers array and add each number to a variable named sum:

userh16xx0's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged python python-3.x or ask your own question .

  • The Overflow Blog
  • Detecting errors in AI-generated code
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Preventing unauthorized automated access to the network
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • dd backup fails with "File too large" error despite ample free space on FAT32 partition
  • How uncommon/problematic is a passport whose validity period (period between issue and expiry) is a non-whole number of years?
  • Pnemautic lift cabinet door won't stay open
  • Is Wild Shape affected by Moonbeam?
  • How to solve this partial differential equation for y?
  • BSS138 level shifter - blocking current flow when high-side supply is not connected?
  • The King takes a stroll
  • Update system python
  • Paired or unpaired t test in two samples of horses and their wound size
  • Does Newton's third law violate the law of energy conservation?
  • How fast to play Rachmaninoff’s Études-Tableaux, Op. 33 No. 5 in G minor?
  • How to return multiple columns from one function inside `mutate` and allow me to name the output columns?
  • Change style of True/False everywhere
  • Using earphones as a dipole antenna
  • The 12th Amendment: what if the presidential and vice-presidential candidates are from the same state?
  • "Some" depicted
  • Why doesn't Spacex use a normal blast trench like Saturn V?
  • Better Methods to Find a Point's Coordinates with Three Collinear Points
  • Is there enough food in the Ocean to support large populations of Octopus?
  • Letter of recommendation conflict of interest
  • Did Microsoft actually release a “Critical Update Notification Tool”?
  • Is an entirely sailing-ship based civilization feasible?
  • What is the difference between k-averaged transmission and gamma point transmission?
  • Could a civilisation develop spaceflight by artillery before developing orbit-capable rockets?

python string assignment by index

IMAGES

  1. Python string index method explanation with example

    python string assignment by index

  2. How To Index and Slice Strings in Python?

    python string assignment by index

  3. the string 'Python' with 6 index numbers 0..5

    python string assignment by index

  4. PythonEasy

    python string assignment by index

  5. Python string index method

    python string assignment by index

  6. Python String Indexing

    python string assignment by index

VIDEO

  1. Indexing Methods in Python

  2. Python: String

  3. String In Python

  4. Python string comparison

  5. String Assignment

  6. How to get the first character of a string in Python

COMMENTS

  1. python

    As strings are immutable in Python, just create a new string which includes the value at the desired index. Assuming you have a string s, perhaps s = "mystring". You can quickly (and obviously) replace a portion at a desired index by placing it between "slices" of the original. s = s[:index] + newstring + s[index + 1:] You can find the middle ...

  2. How do I replace a string at a index in python?

    2. Strings are immutable in Python, so you can't assign like i[0] = 'H'. What you can do is convert the string to list, which is mutable, then you can assign new values at a certain index. i = "hello!" i_list = list(i) i_list[0] = 'H'. i_new = ''.join(i_list) print(i_new) Hello!

  3. How To Index and Slice Strings in Python?

    We use slicing when we require a part of the string and not the complete string. Syntax : string [start : end : step] start : We provide the starting index. end : We provide the end index (this is not included in substring). step : It is an optional argument that determines the increment between each index for slicing.

  4. Python String

    Python - Replace Character at Specific Index in String. To replace a character with a given character at a specified index, you can use python string slicing as shown below: string = string[:position] + character + string[position+1:] where character is the new character that has to be replaced with and position is the index at which we are ...

  5. Python String

    As a string is a collection of characters stored as an ordered sequence, each character is assigned the index position starting with 0. We can access each character by passing the index position in the square brackets.

  6. String Indexing in Python

    Suppose that we have a string "PythonForBeginners". Here, the index of the letter "P" is 0. The index of the letter "y" is 1. The index of letter "t" is 2, The index of letter "h" is 3 and so on. The index of the last letter "s" is 17. In python, we can use positive as well as negative numbers for string indexing. Let us ...

  7. How to Replace Character in String at Index in Python

    In this method, the given string is first converted into a list. After that, the old character is replaced by the new character at the specified index. Finally, the list items are converted to a string using the join() function. The following code uses a List to replace a character in a string at a certain index in Python.

  8. Python String index() Method

    Definition and Usage. The index() method finds the first occurrence of the specified value. The index() method raises an exception if the value is not found. The index() method is almost the same as the find() method, the only difference is that the find() method returns -1 if the value is not found. (See example below)

  9. How To Index and Slice Strings in Python 3

    Learn how to access and manipulate characters in Python strings using index numbers and slices. See examples of positive and negative indexing, and how to use slices to extract substrings.

  10. Python Program to Replace a Character at a Specific Index

    In Python, we can easily replace a character at a specific index by converting the string into a list of characters using the list () method. Then, we modify the character at the desired index and convert the list back to the string using the join () method. We can also replace a character at a specific index using the slicing and replace method.

  11. string

    Learn how to use the string module to format and manipulate strings in Python. See the syntax, methods, and constants of the string module, including the format() method and the Formatter class.

  12. String Indexing (Video)

    00:15 and the individual characters of a string can be accessed directly using that numerical index. String indexing in Python is zero-based, so the very first character in the string would have an index of 0, 00:30 and the next would be 1, and so on. The index of the last character will be the length of the string minus one. Let's look at an ...

  13. Python String index()

    In this tutorial, we will learn about the Python index() method with the help of examples. 36% off. Learn to code solving problems and writing code with our hands-on Python course. ... If substring exists inside the string, it returns the lowest index in the string where substring is found.

  14. Strings and Character Data in Python

    In short, for any non-empty string, s[len(s) - 1] and s[-1] both return the last character. Similarly, s[0] and s[-len(s)] return the first character. Note that no index makes sense on an empty string. Finally, you should keep in mind that because strings are immutable, you can't perform index assignments on them.

  15. Using replace() method in python by index

    This should works: word = "test"; i = word.index('t', 2); word[0:i] + "b" + word[i+1:]. Of course if you know the id of the char you want to replace instead of a letter you can directly set the variable i. If you need to substitue strings you could adapt it using the i+len(substring)+1 to determine where the string ends.

  16. Python Strings (With Examples)

    Python Strings. In Python, a string is a sequence of characters. For example, "hello" is a string containing a sequence of characters 'h', 'e', 'l', 'l', and 'o'. We use single quotes or double quotes to represent a string in Python. For example, # create a string using double quotes. string1 = "Python programming" # create a string using ...

  17. Python

    In the above syntax for the .index() method:. pattern (Required): The pattern or substring to search for.; start (Optional): The starting index of string to search. The default is 0. end (Optional): The index of the slice of string to search up to, non-inclusive. The default is end of the string. Example 1. Use .index() method to search for the occurrence of 'Python' in the string variable my ...

  18. Python String index() Method

    Index of ' and ' in string: 1 Python String Index() Method for Finding Index of Single Character. Basic usage of the Python string index() method is to the index position of a particular character or it may be a word. So whenever we need to find the index of a particular character we use the index method to get it.

  19. Alternative to python string item assignment

    Since strings are "immutable", you get the effect of editing by constructing a modified version of the string and assigning it over the old value. If you want to replace or insert to a specific position in the string, the most array-like syntax is to use slices:

  20. Python String

    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 ...

  21. python

    They are essential to writing idiomatic Python. Share. Improve this answer. Follow edited Oct 19, 2020 at 3:06. answered Oct 19, 2020 at 2:59. Mark Mark. 92.2k 7 7 ... Replace a certain index of a string in python 3.0. 9. Python: String replace index. 2. Append or Add to string of specific index. 1.