Placement Prep

Program to Sort a String in Alphabetical Order in Python

Two Python approaches to sort a string alphabetically: the sorted() built-in and a manual loop. Covers time complexity, case handling, and edge cases.

By FACE Prep Team 4 min read
python string-sorting programming placement-prep coding-problems python-programs

Sorting every character in a string into alphabetical order takes one line in Python: ''.join(sorted(s)). This article covers two complete approaches, case handling, reverse sorting, and edge cases. Each example includes verified outputs ready to use in a placement coding test.

Understanding the Problem

Sorting a string alphabetically means rearranging its characters so they appear in ascending lexicographic order. Python determines that order by each character’s Unicode code point, which for standard English letters matches the ASCII table exactly.

Two examples with verified outputs:

  • Input: "face" — Characters: f(102), a(97), c(99), e(101). Sorted by code point: a(97), c(99), e(101), f(102). Output: "acef"
  • Input: "focus" — Characters: f(102), o(111), c(99), u(117), s(115). Sorted: c(99), f(102), o(111), s(115), u(117). Output: "cfosu"

This problem shows up in entry-level coding tests at companies like TCS and Infosys, and it is also the first step in related problems: anagram detection (sort both strings, compare), character frequency analysis, and pangram checks all rely on the same sorting idea. Pair it with other Python practice programs to build a complete placement prep set.

Method 1: Using sorted() and join()

According to Python’s sorted() documentation, sorted() accepts any iterable and returns a new list of its elements in ascending order. A string is an iterable of individual characters, so sorted("face") returns ['a', 'c', 'e', 'f']. The ''.join() call then concatenates that list back into a single string.

def sort_string(s):
    return ''.join(sorted(s))

print(sort_string("face"))    # acef
print(sort_string("focus"))   # cfosu
print(sort_string("python"))  # hnopty

Output verification:

  • "face": sorted code points 97, 99, 101, 102 → "acef"
  • "focus": sorted code points 99, 102, 111, 115, 117 → "cfosu"
  • "python": h(104), n(110), o(111), p(112), t(116), y(121) → "hnopty"

The Python Sorting How-To explains that sorted() uses Timsort, an adaptive merge-sort variant with O(n log n) worst-case time complexity. Space complexity is O(n) because a new list is created. This is the approach to reach for in any real solution or timed test.

Method 2: Manual Sorting with Nested Loops

A manual approach converts the string to a list of characters, then uses nested loops to compare and swap pairs until every character is in order. This mirrors selection sort and serves as a useful exercise for building intuition about comparison-based sorting.

def sort_string_manual(s):
    chars = list(s)
    n = len(chars)
    for i in range(n - 1):
        for j in range(i + 1, n):
            if chars[i] > chars[j]:
                chars[i], chars[j] = chars[j], chars[i]
    return ''.join(chars)

print(sort_string_manual("focus"))  # cfosu

Step-by-step trace for "focus":

  • Start: ['f', 'o', 'c', 'u', 's']
  • i=0: f(102) is greater than c(99), so f and c swap. Array: ['c', 'o', 'f', 'u', 's']
  • i=1: o(111) is greater than f(102), so o and f swap. Array: ['c', 'f', 'o', 'u', 's']
  • i=2: o(111) is not greater than u(117) or s(115), no swaps.
  • i=3: u(117) is greater than s(115), so u and s swap. Array: ['c', 'f', 'o', 's', 'u']
  • Result: "cfosu"

The list(s) conversion at the start is necessary because Python strings are immutable; you cannot modify individual characters in place. Time complexity is O(n^2) from the two nested loops iterating over n characters.

Comparing the Two Methods

In Python, both methods require O(n) space because the string must be converted to a mutable sequence before sorting. The only meaningful difference is time complexity.

ApproachTime ComplexitySpace ComplexityBest for
sorted() + join()O(n log n)O(n)All practical cases
Manual nested loopO(n^2)O(n)Learning how comparison sort works

Use sorted() for any real code or placement answer. The manual loop is worth writing once to understand the algorithm, then set aside in favour of the built-in.

Handling Case Sensitivity

By default, Python sorts uppercase letters before lowercase because uppercase ASCII codes (65 to 90) are numerically lower than lowercase codes (97 to 122). The comparison 'A' < 'a' evaluates to True in Python.

print(''.join(sorted("Python")))          # Phnoty
print(''.join(sorted("python")))          # hnopty

For "Python": P has code 80, which is lower than h(104), n(110), o(111), t(116), y(121). So P sorts first, giving "Phnoty". The same word in all lowercase gives "hnopty".

To produce alphabetical order that ignores case, convert the string to lowercase before sorting:

print(''.join(sorted("Python".lower())))  # hnopty

If you need to preserve the original case of each character while still sorting by the lowercase value, pass a key argument: sorted(s, key=str.lower). This sorts characters as if they were lowercase but returns the original form.

The character type check guide covers how Python identifies uppercase, lowercase, digit, and special characters in depth, which is useful context for building more selective sorting logic.

Reverse Order and Edge Cases

To sort in reverse alphabetical order, pass reverse=True to sorted():

print(''.join(sorted("face", reverse=True)))   # feca
print(''.join(sorted("focus", reverse=True)))  # usofc

Verification:

  • "face" reversed: f(102), e(101), c(99), a(97) → "feca"
  • "focus" reversed: u(117), s(115), o(111), f(102), c(99) → "usofc"

Edge cases to know before a coding test:

  • Empty string: ''.join(sorted("")) returns "". No error is raised.
  • Single character: ''.join(sorted("z")) returns "z". Works correctly.
  • Spaces: The space character has ASCII code 32, which is lower than any letter code. sort_string("ab cd") returns " abcd" with the space at the front.
  • Digits in the string: Digit characters have codes 48 to 57, which place them after spaces but before uppercase letters. A string mixing letters and digits will sort digits first, then uppercase, then lowercase.
  • Filter before sorting: If the task requires only alphabetical characters, use ''.join(sorted(c for c in s if c.isalpha())) to exclude spaces, digits, and punctuation before sorting.

For a complete reference on basic Python programs like this Python calculator program, the same single-responsibility function pattern applies: one function, one clear task, a print to verify the output.

Sorting characters is one instance of a broader pattern in Python: pass an iterable to sorted(), get back an ordered list, combine with join(). That same pattern, applied to sequences of tokens rather than individual characters, is how tokenizers in large language models prepare text for processing. If you want to move from sorting characters to building tools that work with language models, TinkerLLM is the entry point at ₹299, a hands-on environment where you apply Python string-processing ideas at the scale of real prompts and model outputs.

Primary sources

Frequently asked questions

What is the simplest way to sort a string in Python?

Use ''.join(sorted(s)). The sorted() function returns a list of characters in ascending ASCII order, and join() combines them into a sorted string.

How do I sort a string in reverse alphabetical order in Python?

Pass reverse=True to sorted(): ''.join(sorted(s, reverse=True)). This returns characters in descending alphabetical order.

Why does Python sort uppercase letters before lowercase?

Python's sort uses Unicode code points. Uppercase A to Z have codes 65 to 90, while lowercase a to z run from 97 to 122. Lower code points sort first, so uppercase comes before lowercase by default.

How do I sort a string case-insensitively in Python?

Convert to lowercase first: ''.join(sorted(s.lower())). This normalises all characters to the same case before sorting so uppercase and lowercase do not interfere.

What is the time complexity of sorting a string in Python?

Python's sorted() uses Timsort, giving O(n log n) worst-case time complexity. A manual nested-loop approach has O(n^2) due to double iteration over n characters.

Does sorted() change the original string?

No. Strings in Python are immutable. sorted(s) returns a new list of characters and the original string s is never modified.

Does sorted() handle strings with spaces or digits?

Yes. Spaces have ASCII code 32 and sort before letters. Digit characters (48 to 57) sort before uppercase letters (65 to 90). Filter with s.isalpha() if you only want alphabetical characters.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF