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

时间:2018-10-23 06:31:28

标签: python python-3.x uppercase lowercase

我想随机将字符串中的每个字母大写或小写。我是在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'对象不支持项目分配

但是我还能怎么做呢?

6 个答案:

答案 0 :(得分:22)

您可以将str.join与这样的生成器表达式一起使用:

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

示例输出:

heLlo WORLd

答案 1 :(得分:6)

建立一个新的字符串。

这是一个对原始代码几乎没有更改的解决方案:

>>> 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 Stackoverflow!')
>>> 'hElLo StaCkoVERFLow!'

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

答案 2 :(得分:4)

只需将字符串实现更改为列表实现。由于字符串是不可变的,因此无法更改对象内部的值。但是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)

答案 3 :(得分:3)

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

qUiCK TEsT

答案 4 :(得分:2)

您可以像下面这样

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

答案 5 :(得分:0)

不涉及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到z字符,需要特别注意。在上面的示例中,仅处理了空间

通过替换,您可以同时处理更多特殊字符

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'