随机将字符串中的字母大写

Randomly capitalize letters in string

我想随机将字符串中的每个字母大写或小写。我刚开始使用 python 中的字符串,但我认为因为字符串是不可变的,所以我不能执行以下操作:

i =0             
for c in sentence:
    case = random.randint(0,1)
    print("case = ", case)
    if case == 0:
        print("here0")
        sentence[i] = sentence[i].lower()
    else:
        print("here1")
        sentence[i] = sentence[i].upper()
    i += 1
print ("new sentence = ", sentence)

并得到错误:TypeError: 'str' object does not support item assignment

但是我还能怎么做呢?

import random
sentence='quick test'
print(''.join([char.lower() if random.randint(0,1) else char.upper() \
                   for char in sentence]))

qUiCK TEsT

你可以像下面那样做

char_list = []            
for c in sentence:
    ucase = random.randint(0,1)
    print("case = ", case)
    if ucase:
        print("here1")
        char_list.append(c.upper())
    else:
        print("here0")
        char_list.append(c.lower())
print ("new sentence = ", ''.join(char_list))

您可以将 str.join 与生成器表达式一起使用,如下所示:

from random import choice
sentence = 'Hello World'
print(''.join(choice((str.upper, str.lower))(c) for c in sentence))

示例输出:

heLlo WORLd

建立一个新的字符串。

这是一个对您的原始代码稍作改动的解决方案:

>>> import random
>>> 
>>> def randomcase(s):
...:    result = ''
...:    for c in s:
...:        case = random.randint(0, 1)
...:        if case == 0:
...:            result += c.upper()
...:        else:
...:            result += c.lower()
...:    return result
...:
...:
>>> randomcase('Hello Whosebug!')
>>> 'hElLo Whosebug!'

编辑:删除了我的 oneliner,因为我更喜欢 blhsing。

只需将字符串实现更改为列表实现即可。由于字符串是不可变的,因此您无法更改对象内部的值。但是 Lists 可以,所以我只更改了您的那部分代码。请注意,有更好的方法可以做到这一点,请关注 here

import random
sentence = "This is a test sentence" # Strings are immutable
i =0
new_sentence = [] # Lists are mutable sequences
for c in sentence:
    case = random.randint(0,1)
    print("case = ", case)
    if case == 0:
        print("here0")
        new_sentence += sentence[i].lower() # append to the list
    else:
        print("here1")
        new_sentence += sentence[i].upper() # append to the list
    i += 1
print ("new sentence = ", new_sentence)

# to print as string
new_sent = ''.join(new_sentence)
print(new_sent)

一种不涉及 python 循环的方法是将其发送到 numpy 并对其进行矢量化操作。例如:

import numpy as np
def randomCapitalize(s):
    s  = np.array(s, 'c').view('u1')
    t  = np.random.randint(0, 2, len(s), 'u1') # Temporary array
    t *= s != 32 # ASCII 32 (i.e. space) should not be lowercased
    t *= 32 # Decrease ASCII by 32 to lowercase
    s -= t
    return s.view('S' + str(len(s)))[0]
randomCapitalize('hello world jfwojeo jaiofjowejfefjawivj a jofjawoefj')

输出:

b'HELLO WoRlD jFwoJEO JAioFjOWeJfEfJAWIvJ A JofjaWOefj'

这个解决方案应该相当快,尤其是对于长字符串。这种方法有两个限制:

  • 输入必须完全小写。您可以先尝试 .lower(),但从技术上讲效率很低。

  • 非a-to-z字符需要特别注意。在上面的例子中,只处理了space

你可以通过替换

同时处理更多的特殊字符
t *= s != 32

# using space, enter, comma, period as example
t *= np.isin(s, list(map(ord, ' \n,.')), invert=True)

例如:

s = 'ascii table and description. ascii stands for american standard code for information interchange. computers can only understand numbers, so an ascii code is the numerical representation of a character such as'
randomCapitalize(s)

输出:

b'ascII tABLe AnD descRiptIOn. ascii sTaNds for AmEricAN stanDaRD codE FOr InForMAtION iNTeRCHaNge. ComPUtERS can onLY UNdersTand nUMBers, So An asCIi COdE IS tHE nuMERIcaL rEPrEsEnTATion Of a CHaractEr such as'